Magento 2 – Add Custom Code Before Closing Head Tag

headlayoutmagento2

I am new to Magento.

I have some products in my Magento 2 website. I want to add some custom meta code before closing of head tag.

Example

if (page_id==1){
 some code 
}
if(page_id==2){
other code 
}

So in which php / phtml file have to add this code?**

Best Answer

You can add your meta keywords or description in the product admin section under SEO Content tab.

Or if you want to add your code file in the add then you can add your static block or file in the head with default.xml. Below is an example to add a template file in the head file.

/app/design/frontend/[vendor]/[theme]/Magento_Theme/layout/default.xml

<referenceContainer name="head.additional">
    <block class="Magento\Framework\View\Element\Template" name="custom_head_file" template="Magento_Theme::custom_head.phtml"/>
</referenceContainer>

Add custom_head.phtml file to the below path with your conditional content described below.

/app/design/frontend/[vendor]/[theme]/Magento_Theme/Templates/custom_head.phtml

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cmsPage = $objectManager->get('\Magento\Cms\Model\Page');

$page_id = $cmsPage->getId();

if ($page_id==1){
    //your code for page id 1
}
if($page_id==2){
    //your code for page id 2
}

Hope it helps!