Site icon MageComp Blog

How to Assign Product Position for a Specific Category in Magento 2?

How to Assign Product Position for a Specific Category in Magento 2

Hello Magento Friends,

In this blog, we will learn about How to Assign Product Position for a Specific Category in Magento 2?

As you know, a category is a collection of products of a similar type. The admin can determine how the products can be displayed on the category page. In Magento 2, if you want to change the position of products for a specific category, you can accomplish it using the below-given steps.

Steps to Assign Product Position for a Specific Category in Magento 2:

Step 1: Create a file in your Magento root directory and add the code as given below

<?php 

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
 
$bootstraps = Bootstrap::create(BP, $_SERVER);
$object_Manager = $bootstraps->getObjectManager();
 
$app_state = $object_Manager->get('\Magento\Framework\App\State');
$app_state->setAreaCode('frontend');
 
try
{
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('\Magento\Framework\App\State');
    $appState->setAreaCode('frontend');

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $categoryId = 16;
    $category = $objectManager->get('\Magento\Catalog\Model\CategoryFactory')->create()->load($categoryId);
    $products = $category->getProductsPosition();
       
    // change position for specific product :
    $productId = 72;
    $newposition = 45;
    
    foreach($products as $id=>$value)
    {
            if($id == $productId)
            {
                $products[$productId] = $newposition;
            }
    }

    // change position for all products 
    $newposition = 45;
    foreach($products as $id=>$value)
    {
                $products[$id] = $newposition;
    }

    $category->setPostedProducts($products);    
    $category->save();

}
catch(\Exception $e)
{
    print_r($e->getMessage());
}

Output:

Using this, you can assign positions to a category using a specific product id. You can also assign positions to more than one product with this code. Based on your requirement, you can assign value for batch products or collections.  

Conclusion:

This way, you can Assign Product Positions for a Specific Category in Magento 2. Check out How to Load Products by Product ID and SKU in Magento 2. If you face any hardship in assigning the product position programmatically, you can freely ask me through the comment part. Share the article with your Magento friends and hold on with us to not miss out on our latest tutorials.

Happy Coding!

Exit mobile version