How To

How to Remove cart item Automatically after 30 Minutes in Magento 2

Hello, Magento Fans,

Last time we learned how you can show the list of all categories at the sidebar for Magento 2.

Today we are going to learn about how you can remove the item from the cart automatically after 30 minutes.

In the rising world of Ecommerce, the work of developers is to make things fast, smart, and easy with their coding knowledge. As developers, we are destined to play around with numerous codes and numbers to save time and efforts of our clients and end-users. To stay ahead in the game, Ecommerce store owners have become demanding and want to add tons of new features and functions to their store.

While doing one project, we came across the requirement of the client to remove the cart item automatically after 30 Minutes. As a developer, we regularly come across such situations, so we thought of penning it down on our blog page.

Using the below codes, you can remove cart items automatically after 30minutes.

Step 1: First, we need to create a “Registration.php” file inside our extension at the following path..
app\code\Vendor\Extension

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_Extension',
    __DIR__
);

Step 2: After that, we need to create a “Module.xml” file inside extension etc folder. app\code\Vendor\Extension\etc

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Extension" setup_version="1.0.0" schema_version="1.0.0">
    </module>
</config>

Step 3: After that, we need to create “crontab.xml” file inside extension etc folder. app\code\Vendor\Extension\etc

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="removecart" instance="Vendor\Extension\Cron\Removecart" method="getItemData">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

Step 4: Lastly, Create the “Removecart.php” file inside the Cron folder of extension. app\code\Vendor\Extension\Cron

<?php
namespace Vendor\Extension\Cron;

class Removecart {

    /**
     * @var \Magento\Quote\Model\QuoteRepository
     */    protected $quoteRepository;

    /**
     * @var \Magento\Quote\Model\ResourceModel\Quote\CollectionFactory
     */    protected $quoteCollectionFactory;

    public function __construct(
        \Magento\Quote\Model\ResourceModel\Quote\CollectionFactory $quoteCollectionFactory,
        \Magento\Quote\Model\QuoteRepository $quoteRepository
    ) {

        $this->quoteCollectionFactory = $quoteCollectionFactory;
        $this->quoteRepository = $quoteRepository;
    }
    public function getItemData()
    {
        $fromTime = new \DateTime('now', new \DateTimezone('UTC'));
        $fromTime->sub(\DateInterval::createFromDateString('30 minutes'));

        $fromDate = $fromTime->format('Y-m-d H:i:s');
        $quoteCollection = $this->quoteCollectionFactory->create();

        $quoteCollection
            ->addFieldToFilter('created_at', ['lteq' => $fromDate]);

        if($quoteCollection->getSize() >0){
            foreach ($quoteCollection as $quote)
            {
                $quoteFullObject = $this->quoteRepository->get($quote->getId());
                $quoteFullObject->delete();
            }
        }


    }
}

If you have to execute this code on your site, then execute all codes in your root command. If you have executed all codes successfully, then run the below command in your command prompt.

php bin/magento cron:install

php bin/magento cron:run

Every 30 minutes, the cron is executed. If there is an item available in the cart, it will be then removed Automatically.

So, that was all for the day! With the help of these codes, you can successfully achieve the task of removing cart items automatically after every 30 minutes in Magneto 2. You are free to play around and customize these codes according to your needs of fetching data. If you face any issues while implementing, then contact our support team. We will be happy to help you.

Lastly, if you found this helpful, then let us know in the comments below. Also, don’t forget to share this with your Magento partners.

Click to rate this post!
[Total: 4 Average: 4.5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

  • what if I add an item in a cart now and again add item in a cart after 15 min, Then both will remove at a same time?

    • This will remove the cart after the given time from the first creation because when you add another item it will update only that updated_at field, not created_at.

  • Hello team,
    i am unable to get result using this line change
    $fromTime->sub(\DateInterval::createFromDateString('5 minutes'));
    is it working? or need to change some formate

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

2 hours ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

2 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

2 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

3 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

6 days ago