Inserting META Tags in WordPress Themes Without Plugins

Posted on in Programming

In his excellent series on WordPress Theme SEO, Nathan Rice describes a method to include META tags in WordPress themes rather than relying on plugins. Since I recently updated the Slaptijack theme to include META descriptions and keywords, I thought I would detail the process. If you are interested in improving the <acronym title="Search Engine Optimization">SEO</acronym> aspects of your WordPress theme, I recommend checking out Nathan's article series on the subject.

<!--more-->

The first thing I did was create a new function in my theme's functions.php file. As you can see below, this code is taken directly from Nathan's META Keywords post. I used trim to remove the trailing ',' from the string of keywords.

function csv_tags() {
  $posttags = get_the_tags();

  foreach((array)$posttags as $tag) {
    $csv_tags .= $tag->name . ',';
  }

  $csv_tags = trim($csv_tags, ',');

  echo '<meta name="keywords" content="' . $csv_tags . '" />';
}

Next I added the following code into my theme's header.php file:

<?php if ( is_single() || is_page() ) : if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  <meta name="description" content="<?php the_excerpt_rss(); ?>" />
  <?php csv_tags(); ?>
<?php endwhile; endif; elseif ( is_home() ) : ?>
  <meta name="description" content="<?php bloginfo('description'); ?>" />
<?php elseif ( is_category() && category_description() ) : ?>
  <meta name="description" content="<?php echo trim(strip_tags(category_description())); ?>" />
<?php endif; ?>

Again, this is a modified version of what Nathan did in his META descriptions post. I added an extra check for category pages that prints the category description. The most important thing to remember here is that the the_excerpt_rss() template tag is only available inside The Loop. We make this available in our header via the while ( have_posts() ) : the_post(); endwhile; construct. This only happens on pages and posts, so there is not a lot of extra database overhead added by doing this.

Slaptijack's Koding Kraken