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,

This Blog will focus on how to filter order collections in Magento 2 by specific product name.

If you want to filter order collections dependent on specific product item name, there are occasions when this can be helpful, and that’s delivering reports, analyzing the sales data, even analyzing targeted marketing campaigns for products of your Magento 2 store.

Following the steps below allows you to get orders with a particular product.

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 ✨