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



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());

}

Comments

Popular posts from this blog

Add Admin User name and Action name in Order Comment Section through Action Performed from Sales Order Grid in Magento 2

How to Update Product Stock Programmatically in Magento 2

How to Set and Get Cookie in Magento 2