4

I would like to add CMS block to a category programmatically, how to achieve it?

  • 1
    This post appears to be off-topic as per Questions asking for code must demonstrate a minimal understanding of the problem being solved. Please include your expected results, your attempted solutions, and why they didn't work. Please see the Stack Overflow question checklist for more details. – Philipp Sander Mar 14 at 14:00
2

In order to add a cms block to the Category page, first, you already have cms static block.

If you want to add CMs block to the category then set have to set cms block identifier to of category and display mode of category page should be Static block only PAGE and Static block and products PRODUCTS_AND_PAGE.

Sample code

<?php

namespace StackExchange\Magento\Test;


class CmsBlock {

    /**
     * @var \Magento\Catalog\Model\CategoryFactory
     */
    private $categroyFactory;

    public function __construct(
     \Magento\Catalog\Model\CategoryFactory $categroyFactory
    ) {

        $this->categroyFactory = $categroyFactory;
    }

 public function saveCMSBlockToCategory()
    {
     $catId = 10;
        $storeId = null; // You can put your store id  here
        $category = $this->categroyFactory->create();
        if (null !== $storeId) {
            $category->setStoreId($storeId);
        }
        $category->load($catId);
        if($category->getId()){
            $category->setData('landing_page',2);
            $category->setData('display_mode','PRODUCTS_AND_PAGE');
            $category->save();
        }
    }
}

NOte

Not using Service contact class \Magento\Catalog\Api\CategoryRepositoryInterface as on save method its has magento bug.

Bug link: https://github.com/magento/magento2/issues/10088

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.