There are plenty of great SEO plugins out there, but if you want absolute control over your website here’s a fast function to add your own META tags to a WordPress website.
<?php
if (is_single()) {
global $post;
foreach((wp_get_post_tags($post->ID)) as $tags) {
$t .= “, “.$tags->name;
}
echo “<meta title=’description’ value=’”.$post->post_excerpt.’;”;
echo “<meta title=’keywords’ value=’$t’>”;
}
?>
if (is_single()) {
global $post;
foreach((wp_get_post_tags($post->ID)) as $tags) {
$t .= “, “.$tags->name;
}
echo “<meta title=’description’ value=’”.$post->post_excerpt.’;”;
echo “<meta title=’keywords’ value=’$t’>”;
}
?>
That example will allow you to place the excerpt in the description meta tag, while placing your keywords as comma separated text in the keyword meta tags.
If you want to make the code a little more complicated, but a lot more accurate for SEO purposes, you should add the post’s categories to the list as well.
foreach((get_the_category()) as $category) {
$c .= “, “.$category->cat_name;
}
$c .= “, “.$category->cat_name;
}
Here’s the final code, place this in the functions.php file of your website (located in /wp-content/themes/[your theme name]/) and the meta tags should appear on single posts.
<?php
function thisismyurl_meta_tags (){
if (is_single()) {
global $post;
foreach((wp_get_post_tags($post->ID)) as $tags) {
$t .= “, “.$tags->name;
}
foreach((get_the_category($post->ID)) as $category) {
$c .= “, “.$category->cat_name;
}
echo “<meta title=’description’ value=’”.$post->post_excerpt.”‘>”;
echo “<meta title=’keywords’ value=’$t.$c’>”;
}
}
add_filter( ‘wp_head’, ‘thisismyurl_meta_tags’ );?>
function thisismyurl_meta_tags (){
if (is_single()) {
global $post;
foreach((wp_get_post_tags($post->ID)) as $tags) {
$t .= “, “.$tags->name;
}
foreach((get_the_category($post->ID)) as $category) {
$c .= “, “.$category->cat_name;
}
echo “<meta title=’description’ value=’”.$post->post_excerpt.”‘>”;
echo “<meta title=’keywords’ value=’$t.$c’>”;
}
}
add_filter( ‘wp_head’, ‘thisismyurl_meta_tags’ );?>
Nice post but if I wanted to add different tags to specific pages, how would I do that?
Hi Randy, you could do the same to pages by replacing the is_single() with is_page().