How to Filter Order Collection by Specific Product Item Name in Magento 2?

How to Filter Order Collection by Specific Product Item Name in Magento 2

Hello Magento Friends,

In this blog post, we will explore how to filter order collections in Magento 2 based on a specific product item name.

Filtering order collections based on specific product item names can be useful in various scenarios, such as generating reports, analyzing sales data, or performing targeted marketing campaigns for your Magento 2 store.

By following the steps outlined below, you’ll be able to retrieve orders containing a particular product efficiently.

Steps to Filter Order Collection by Specific Product Item Name in Magento 2:

Step 1: Create a file in your Magento root directory at the below path

magento_root_directory\getOrderItem.php

Then add the code as follows

<?php
use Magento\Framework\App\Bootstrap;
require_once __DIR__ . '/../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

try {
	$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
	$productname='test 2'; // Replace with product name you want to search
	$orderdata = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory')->create()->addAttributeToSelect('*');
	$orderdata->getSelect()->join(array('order_item' => 'sales_order_item'),'main_table.entity_id = order_item.order_id');
	$orderdata->addFieldToFilter('order_item.name', array(array('like' => '%'.$productname.'%')));
	echo "<pre>";
	print_r($orderdata->getdata());
	echo "</pre>";
}
catch (\Exception $e){
    echo "Exception Throw \n";
    echo $e->getMessage() . " \n";
}

Output:

It will print all order data filter by given product name.

order collection

Conclusion:

By following the steps outlined in this blog post, you can easily retrieve orders that contain a particular product item. Whether you’re generating reports, analyzing sales data, or planning targeted marketing campaigns, this technique will help you gain valuable insights from your Magento 2 store.

You can also Get Orders Collection Between a Date Range in Magento 2.

Share the tutorial with your friends, and stay in touch with us.

Happy Coding!

Previous Article

The Benefits of Shopify Plus for Former Magento Users

Next Article

How to Add Sign Out Tab in Customer Account in Magento 2?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨