WordPress tip #6 – calling the post Excerpt in the page head

Referencing the Excerpt in WordPress can ususally be achieved easily simply by via the_excerpt() and get_the_excerpt(). This tutorial shows how to referrence the excerpt in header.php, before going on to show how to achive the same thing via functions.php.

This post was prompted by writing a function, placed in header.php, to allow the automatic creation of Meta Descriptions. It turns out that neither the_excerpt() nor get_the_excerpt() will work in the document head, and it was necessary to use the following code:


<?php
global $post;		// reference the post
$excerpt = $post->post_excerpt;		// retrieve the post's excerpt
?>

The complete code for a very simple automated Meta Description generator might look like this:


<?php
global $post;		// reference the post
$metaDesc = $post->post_excerpt;        // retrieve the post's excerpt
echo '<meta name="Description" content="' . $metaDesc . '" />'
?>

However, there’s always a yet neater way. In this case it turns out that placing everything within a function, in functions.php, and calling it from header.php allows get_the_excerpt() to function as it should. So, in functions.php:


<?php
function my_metaDesc() {
global $post;		// reference the post
$metaDesc = get_the_excerpt();		// retrieve the post's excerpt
echo '<meta name="Description" content="' . $metaDesc . '" />'
}
?>

and in header.php a function call:


<?php if (function_exists(my_metaDesc)) echo my_metaDesc(); ?>

The full meta description function does a lot more that the code shown above, and full details my appear in a subsequent post.

It’s possible to get neater still. If your theme’s header.php contains the wp_head() hook, add_filter() can be used to add the output of the function to header.php without the function call. In header.php:


<?php wp_head(); ?>

and, in functions.php:


<?php
function my_metaDesc() {
global $post;		// reference the post
$metaDesc = get_the_excerpt();		// retrieve the post's excerpt
echo '<meta name="Description" content="' . $metaDesc . '" />'
}

add_filter('wp_head', 'my_metaDesc', 1);
?>

add_filter() supports 4 parameters (see link below). 2 are compulsory, $tag (wp_head in this case), $function_to_add (my_metaDesc in this case). $priority, which is optional, sets a priority. In this case ’1′ should ensure the Meta Description is placed higher in the head than anything else.

Futher reading

Tags: