Is there plugin (or an easyish way) to add code to the <head> section on a per page/post basis?

I have a multilingual website and I need to implement the rel=”alternate” hreflang markup, so need a way to define rel="alternate" individually on each page/post.

I have searched the WordPress plugins but haven’t found any thing thus far. I’m not really a coder so can’t create something myself, unless it was rather easy!

UPDATE

OK, I’m having a go myself trying to create a custom field for this functionality, this is what I have so far:

<link rel="alternate" href="https://wordpress.stackexchange.com/questions/110260/<?php
    while (have_posts()) : the_post();
        $alternate = get_post_meta($post->ID,"alternate', false);
        if ($alternate) {
            echo $alternate[0];
        }
    endwhile;
?>" hreflang="<?php
    while (have_posts()) : the_post();
        $hreflang = get_post_meta($post->ID, 'hreflang', false);
        if ($hreflang) {
            echo $hreflang[0];
        }
    endwhile;
?>" />

Now this works fine if I only want to add one alternate page. When I try to add any more, it will only add one instance of rel="alternate", with the last added replacing the original.

Also, on any pages that I haven’t defined any of these custom fields, I’m getting an empty tag:

<link rel="alternate" href="" hreflang="" />

Can someone please point me in the right direction to correct these issues?

5 Answers
5

As you said per page/post basis, this would work for each post

add_action('wp_head', 'add_link_in_head');
function add_link_in_head()
{
    global $post;
    if(!empty($post))
    {
        $alternate = get_post_meta($post->ID, 'alternate', true);
        $hreflang = get_post_meta($post->ID, 'hreflang', true);
        if(!empty($alternate) && !empty($hreflang))
        {
            ?>
                <link rel="alternate" href="https://wordpress.stackexchange.com/questions/110260/<?php echo $alternate; ?>" hreflang="<?php echo $hreflang; ?>" />
            <?php
        }
    }
}

If there is no $alternate and $hreflang then there would be no link.

Leave a Reply

Your email address will not be published. Required fields are marked *