3

I need to create static blocks programmatically. How to assign a block to selected store views?

I've found tutorials about creating static blocks, but they all add the block to all store views, like this:

public function createCmsBlock()
{
    // $this->blockFactory is of type: \Magento\Cms\Model\BlockFactory
    $cmsBlock = $this->blockFactory->create();
    $cmsBlock->setIdentifier('block-identifier')
        ->setTitle('Block Title')
        ->setContent('Block Content')
        ->setIsActive(true)
        ->setStores([0]);
    $cmsBlock->save();
}

As far as I understand the line ->setStores([0]); adds the block to all store views. But how to force it to add our block only to selected store views? And how to retrieve list of such store views?

2
  • 1
    magento.stackexchange.com/questions/127495/…. U need to get current store view & use that. Magento\Store\Model\StoreManagerInterface from u get storeId
    – Jackson
    Apr 27 '17 at 10:00
  • The ->setStores([0]), add a comma and add your specific store ID here to associate with specific store only. Sep 20 '19 at 6:03
-1

An easy approach to do this is from the Admin Panel:

Content > Blocks > Edit (The Block in Question)

In the edit page you will see it's assigned to all stores/website. Use Ctrl key and select the stores you want it to display.

You can use the same approach to assign different text/language to different store views buy creating another block with same identifier but different content and assigned to different store-views.

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.