How to fetch 5 bestsellers products programmatically in Magento?

Mage::getResourceModel(‘reports/product_collection’)
->addOrderedQty()
->addAttributeToSelect(‘*’)
->setPage(1, 5)
->load();

To fetch the 5 best-selling products programmatically in Magento, you can use the following code:

php
<?php
// Load Magento's app bootstrap
require_once('app/bootstrap.php');

// Bootstrap Magento
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

// Create Object Manager
$objectManager = $bootstrap->getObjectManager();

// Set the state (area) of the application
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

// Get the product collection
$productCollection = $objectManager->create('Magento\Reports\Model\ResourceModel\Report\Collection\Factory');
$collection = $productCollection->create('Magento\Sales\Model\ResourceModel\Report\Bestsellers\Collection');

// Limit the collection to 5 best-selling products
$collection->setPageSize(5);

// Load the collection
$bestSellers = $collection->load();

// Iterate through the collection to get product data
foreach ($bestSellers as $product) {
echo "Product ID: " . $product->getProductId() . "\n";
echo "Product Name: " . $product->getProductName() . "\n";
echo "Product SKU: " . $product->getProductSku() . "\n";
echo "Product Price: " . $product->getProductPrice() . "\n";
// You can add more attributes as needed
echo "\n";
}

This code fetches the best-selling products by utilizing Magento’s built-in reports. It initializes Magento, sets the area code, retrieves the best-selling product collection, limits it to 5 products, loads the collection, and then iterates through each product to display its information.