Thredolsen
Thredolsen

Reputation: 257

How to display a meta description on a site's homepage

What I'm trying to do:

Add a meta description to my WordPress website homepage.

Under what conditions:

The homepage normally has my latest posts on it, so that search engines pick up the description on the latest blog post as the meta description for the site itself.

My goal is to only specify a meta description for the homepage, and not for any of the other posts/pages.

This description needs to be text that isn't available in other areas of the site (i.e. not in the bloginfo() function).

I'm trying to do this using my own plugin, so that I don't have to modify the header.php file directly (since this would mean that I have to modify it each time WP is updated), and so that I don't have to use an external plugin.

There are a few existing questions on the topic (e.g. this one), but none of them explains how to do this exactly.

Upvotes: 4

Views: 898

Answers (1)

Thredolsen
Thredolsen

Reputation: 257

The solution is to use an action hook which inserts the necessary code into the header:

<?php    
function add_meta_home() { 
    if (is_home() || is_front_page()) { ?>
        <meta name="description" content="Lorem ipsum dolor sit amet."/>
        <?php
        }
    }
add_action('wp_head', 'add_meta_home');
?>

The following code is a similar variation of this, which accomplishes the same goal, though the above version is preferable:

<?php    
function add_meta_home() { 
if( is_home() || is_front_page() ){
    $meta_des = "Lorem ipsum dolor sit amet.";
    echo '<meta name="description" content="' . $meta_des . '" />';
    }
}
add_action('wp_head', 'add_meta_home');
?>

This question explains the difference between is_home and is_front_page. I specified both because I wanted to display the same meta description for the main page of the site regardless of its configuration.

To check that this solution worked, go to your homepage and right click -> 'Page source' and search for the meta description there. To double-check, you can also use a site which confirms that your website has a meta description specified.

Also, after applying this change, make sure that you are not viewing a cached version of your website, or you won't be able to see the change.

Upvotes: 3

Related Questions