How to Get Cross Sell Products Collection using Root Script in Magento 2?

How to Get Cross Sell Products Collection using Root Script in Magento 2

Hello Magento Friends,

Today I am here with another solution, How to Get Cross Sell Products Collection using Root Script in Magento 2?

To boost sales, website owners can display Cross-sell, Up-sell, and related products to customers. Learn How to Setup Cross-Sell, Up-Sell, and Related products in Magento 2.

Cross-sell products are displayed with tags like “more choices”, “people also buy”, etc. Cross-sell products are displayed in the shopping cart before checkout. If you want to get the collection of cross-selling products in Magento 2, you can get it using the root script.

Let’s take a closer look at How to Get Cross Sell Products Collection using Root Script in Magento 2?

Steps to Get Cross Sell Products Collection using Root Script in Magento 2:

Step 1: Create a root script for cross-sell product collection as follows.

<?php
 
use Magento\Framework\AppInterface;
 
try
{
   require '../app/bootstrap.php';
}
catch (\Exception $e)
{
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try
{
	$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
	$objectManager = $bootstrap->getObjectManager();
	$appState = $objectManager->get('Magento\Framework\App\State');
	$appState->setAreaCode('frontend');
        $productId = 3; // Product Id
        $crossSellProduct = [];
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface')->getById($productId);
        $crossSell = $product->getCrossSellProducts();
        if (count($crossSell))
        {
                foreach ($crossSell as $productItem)
                {
                     $crossSellProduct[] = $productItem->getSku() . '<br />';  
                     print_r($crossSellProduct);
                }
        } 
}
catch(\Exception $e)
{
    print_r($e->getMessage());
}

Conclusion:

Therefore, the above method can effortlessly help you get a collection of cross-selling products in Magento 2. If you cannot get the desired results, let me know through the comment section. Share the tutorial with your friends, and stay in touch with us for more Magento 2 solutions.

Happy Coding!

Previous Article

Configuration of VAT ID Validation in Magento 2

Next Article

How to Get Product Multi Source Inventory (MSI) Programmatically in Magento 2

Write a Comment
  1. Great article on how to get cross-sell products collection using root script in Magento 2! Thank you for sharing your knowledge and experience with us.

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 ✨