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?
1 Answer 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.
Explore related questions
See similar questions with these tags.
Magento\Store\Model\StoreManagerInterfacefrom u get storeId