I need to insert hreflang tags in the head tags, but I only need these on the homepage. At the moment I'm inserting the hreflang tags into the head via the html.tpl.php template, but this puts the code on all pages in the site. How can I edit the head for just one page? I'm using Drupal 7.
4 Answers
You can use:
<?php if ($is_front): ?>
<!-- code here-->
<?php endif; ?>
In your html.tpl.php and it'll only affect the homepage.
-
are you sure $is_front available in
html.tpl.php
by default? drupal.org/node/1728208– YuseferiCommented Jul 18, 2016 at 7:30
You can set the condition for front page in html.tpl.php, so set your required flag. Use the condition like:
<?php
if (drupal_is_front_page()){
// print the desired code
}
?>
I suggest you three solution.
Duplicate your
html.tpl.php
and rename one of them tohtml--front.tpl.php
, apply your change( hreflang tags ) then clear the cache.another solution is with simple condition apply what you want in
put your markups herehtml.tpl.php
, I mean
But $is_front not exists in html.tpl.php varibles and by default available in page templates,you can add it manually by using template_preprocess_html
function hook_preprocess_html(&$vars) {
$vars['is_front'] = drupal_is_front_page();
}
- use PHP function in your
html.tpl.php
( although if you use PHP function in theme, you should forget using PHP in template in Drupal 8 )
<?php if (drupal_is_front_page()): ?>
put your markups here
<?php endif; ?>
use html_head_alter in template.php and add conditions
function your theme_html_head_alter(&$head_elements) {
$remove = array(
'apple-touch-icon57',
'apple-touch-icon72',
'apple-touch-icon114'
);
foreach ($remove as $key) {
if (isset($head_elements[$key])) {
unset($head_elements[$key]);
}
}
//add
$appleIcon57px = array('#tag' => 'link', '#type' => 'html_tag', '#attributes' => array('rel' => 'apple-touch-icon', 'href' => '/misc/AMU-NUMERIQUE-ICONE-57.png', 'type' => 'image/png', 'media' => 'screen and (resolution: 163dpi)'),);
$appleIcon72px = array('#tag' => 'link','#type' => 'html_tag', '#attributes' => array('rel' => 'apple-touch-icon', 'href' => '/misc/AMU-NUMERIQUE-ICONE-72.png', 'type' => 'image/png', 'media' => 'screen and (resolution: 132dpi)'),);
$appleIcon114px = array('#tag' => 'link','#type' => 'html_tag', '#attributes' => array('rel' => 'apple-touch-icon', 'href' => '/misc/AMU-NUMERIQUE-ICONE-114.png', 'type' => 'image/png', 'media' => 'screen and (resolution: 326dpi)'),);
$head_elements['apple-touch-icon57']=$appleIcon57px;
$head_elements['apple-touch-icon72']=$appleIcon72px;
$head_elements['apple-touch-icon114']=$appleIcon114px;
}