Magento 2 | Add CMS block in a phtml file

December 5th, 2018

I need add a CMS blocks in header of default “Lumia” theme of Magento 2, i want that the content add by block be edited in backend:
We need two steps,

  1. 1° create the CMS Block
  2. 2° Add the cms block to the right .phtml file

Let’s start by entering in “Debug Mode”, and create the CMS Block by navigate to “Content => Block” and add on “Add new block”.

Compile the “add block” form in every parts, add some html ( or the content you need add in this block ),

and save.
Now, ( i want to add the block in header ), open, header.phtml ( if can’t find, follow the suggest that you see in debug mode ), and add, where you want the block appears, this snippet:

echo '<li class="greet social_top" style="position: absolute; left: 2rem;">'; // open the block wrapper
echo $block->getLayout()
           ->setBlockId('header_top_links') // This is the block identifier that you had assign when you have created the block.
echo '</li>'; // Close the block wrapper


Now Empty the cache ( by navigate to “System => Cache management” ), and reload the page, if all is right you see the new block contents.

That’s all, exit from “Debug Mode”, and reload page, if you had added it in header, you see something like this: