1

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?**

3

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!

  • but where is the if condition ? . I wan to insert different code on head for different page . so using page id i have to write if condition . – John Aug 27 at 9:17
  • I've updated my code, please have a review. – Sumit Aug 27 at 9:25
  • thank you . I will check this – John Aug 27 at 9:29
0

copy below code in default.xml without <body> or find head.additional paste below block with create one file i.e : headcontent.phtml than add your php code in phtml file.

<body>
    <referenceBlock name="head.additional">
        <block class="Magento\Framework\View\Element\Template" name="helpout" template="Magento_Theme::headcontent.phtml"/>
    </referenceBlock>
</body>

than create headcontent.phtml with your html code :

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

    $page_id = $cmsPage->getId();

   if (page_id==1){
     some code 
    }
    if(page_id==2){
    other code 
    }
  • but where is the if condition ? . I wan to insert different code on head for different page . so using page id i have to write if condition . – John Aug 27 at 9:17
  • i update my code. – Anas Mansuri Aug 27 at 9:25
  • thank you . I will check this – John Aug 27 at 9:29

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.