{"id":2273,"date":"2023-09-11T07:30:52","date_gmt":"2023-09-11T07:30:52","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/programmatically-set-product-position-in-a-category-in-magento-2\/"},"modified":"2025-05-21T18:17:34","modified_gmt":"2025-05-21T12:47:34","slug":"programmatically-set-product-position-in-a-category-in-magento-2","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/programmatically-set-product-position-in-a-category-in-magento-2\/","title":{"rendered":"Programmatically Set Product Position in a Category in Magento 2"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The product position value determines the order of products on the category page. The product position value of new products in a category is preset to zero.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By default,&nbsp;<a href=\"https:\/\/business.adobe.com\/products\/magento\/magento-commerce.html\" target=\"_blank\" rel=\"noreferrer noopener\">Magento<\/a>&nbsp;displays the products in a descending position on the category pages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, 10, 9, 8\u2026 0.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Therefore, all new products are displayed at the bottom of the list. You can manually change these product position values from the&nbsp;<strong>Edit Category &gt; Products<\/strong>&nbsp;in the Category section.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" src=\"https:\/\/meetanshi.com\/blog\/wp-content\/uploads\/2023\/07\/Product-position-in-category.png\" alt=\"Set product position programmatically in magento 2 category\" class=\"wp-image-33170\"\/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">category in Magento 2\u201d width=\u201d700\u2033 height=\u201d356\u2033 \/&gt;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">But what if you want to&nbsp;<em><strong>programmatically set product position in a category in Magento 2<\/strong><\/em>?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can do that by creating a custom module!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this post, we\u2019ll learn to assign product positions for a specific category of Magento 2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Earlier, we showed you the method to&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/sort-magento-2-category-products-by-stock-quantity\/\" target=\"_blank\" rel=\"noreferrer noopener\">sort products by quantity in Magento 2<\/a>, do check it out!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Method to Programmatically Set Product Position on Category Page in Magento 2<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You can programmatically set product positions on category pages in Magento 2 through a custom module. Here\u2019s how to do it:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, create a&nbsp;<strong>module.xml<\/strong>&nbsp;file at the&nbsp;<em><strong>vendor\/module\/etc\/<\/strong><\/em>&nbsp;directory.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:Module\/etc\/module.xsd\">\n    &lt;module name=\"Meetanshi_PositionProducts\" active=\"true\" schema_version=\"1.0.1\" setup_version=\"1.0.1\">\n    &lt;\/module>\n&lt;\/config><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Create&nbsp;<strong>registration.php<\/strong>&nbsp;file inside the&nbsp;<em><strong>vendor\/module\/<\/strong><\/em>&nbsp;folder.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;MagentoFrameworkComponentComponentRegistrar::register(\n    MagentoFrameworkComponentComponentRegistrar::MODULE,\n    'Meetanshi_PositionProducts',\n    __DIR__\n);<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Add&nbsp;<strong>events.xml<\/strong>&nbsp;file at the&nbsp;<em><strong>vendor\/module\/etc<\/strong><\/em>&nbsp;directory.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:Event\/etc\/events.xsd\">\n    &lt;event name=\"catalog_product_save_after\">\n        &lt;observer name=\"meetanshi_set_product_position\" instance=\"MeetanshiPositionProductsObserverSetProductPositions\" \/>\n    &lt;\/event>\n&lt;\/config><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now, add the following code inside the&nbsp;<em><strong>vendor\/module\/Observer\/SetProductPositions.php<\/strong><\/em>&nbsp;file for the observer:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;namespace MeetanshiPositionProductsObserver;\n\nuse MagentoFrameworkEventObserver;\nuse MagentoFrameworkEventObserverInterface;\nuse MagentoCatalogModelProduct;\nuse MagentoCatalogModelResourceModelProductCollectionFactory as ProductCollectionFactory;\nuse MagentoStoreModelStoreManagerInterface;\nuse MagentoCatalogModelCategoryFactory;\nuse MagentoCatalogModelResourceModelCategory as CategoryResource;\n\n\nclass SetProductPositions implements ObserverInterface\n{\n    \/**\n     * @var ProductCollectionFactory\n     *\/\n    private $productCollectionFactory;\n     \/**\n     * @var StoreManagerInterface\n     *\/\n    protected $storeManager;\n\n    \/**\n     * @var CategoryFactory\n     *\/\n    protected $categoryFactory;\n\n    \/**\n     * @var CategoryResource\n     *\/\n    protected $categoryResource;\n\n    public function __construct(ProductCollectionFactory $productCollectionFactory,  StoreManagerInterface $storeManager,\n    CategoryFactory $categoryFactory,\n    CategoryResource $categoryResource)\n    {\n        $this->productCollectionFactory = $productCollectionFactory;\n        $this->categoryFactory = $categoryFactory;\n        $this->categoryResource = $categoryResource;\n        $this->storeManager = $storeManager;\n    }\n\n    public function execute(Observer $observer)\n    {\n        $product = $observer->getEvent()->getProduct();\n        \/\/ Get the category ID of the new product.\n        $categoryIds = $product->getCategoryIds();\n        MagentoFrameworkAppObjectManager::getInstance()\n        ->get(PsrLogLoggerInterface::class)->info(print_r($categoryIds,true));\n        \/\/ Get the new product position.\n        $newPosition = 500;\n\n        \/\/ Change the product position.\n        if ($product->isObjectNew()) {\n            MagentoFrameworkAppObjectManager::getInstance()\n            ->get(PsrLogLoggerInterface::class)->info('New product');\n            $this->changeProductPosition($categoryIds, $product->getId(), $newPosition);\n        } else {\n            MagentoFrameworkAppObjectManager::getInstance()\n            ->get(PsrLogLoggerInterface::class)->info('Old product');\n        }\n    }\n    private function changeProductPosition($categoryIds, $productId, $newPosition)\n    {\n       foreach($categoryIds as $categoryId)\n       {\n        MagentoFrameworkAppObjectManager::getInstance()\n        ->get(PsrLogLoggerInterface::class)->info(print_r($categoryId,true));\n        $category = $this->categoryFactory->create()->load($categoryId);\n        $products = $category->getProductsPosition();\n        $products[$productId] = $newPosition;\n        $category->setPostedProducts($products);\n\n        $category->save();\n       }\n        \n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Tweak the&nbsp;<code>$newPosition<\/code>&nbsp;value per your needs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the above module, the event is triggered when a new product is saved in the category. Then the position of the newly added product is changed to the defined value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That\u2019s it! This is how you can programmatically set product position in a category in Magento 2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Found this solution helpful? Share it with your friends.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank You!  <\/p>\n","protected":false},"excerpt":{"rendered":"<p>The product position value determines the order of products on the category page. The product position value of new products in a category is preset&#8230;<\/p>\n","protected":false},"author":13,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-2273","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2273","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=2273"}],"version-history":[{"count":3,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2273\/revisions"}],"predecessor-version":[{"id":14115,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2273\/revisions\/14115"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=2273"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=2273"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=2273"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}