WordPress: Use Custom Fields To Add Keyword Metadata to Your Posts

Posted by & filed under Code Mode.

Keywords at edwardstafford.com

Keywords for edwardstafford.com

One of the short-comings with using WordPress is that it does not provide an easy, built-in way to include metadata for your web page descriptions and keywords (and rightfully so). Why Not? The reason is simply that WordPress cannot read your mind. I know it’s hard to believe when you consider what you can do with wordpress, but it’s true. The issue with Description and Keyword page metadata is that, to be truely effective, it should be created to  describe the content found on each individual page. It’s how search engines like google determine how to categorize and index each page. Now, there are some SEO “experts” who will argue that this information is not very relevant anymore, and I do agree with that for the most part, but there are still SEO benefits to including this metadata vs. not including it at all.

I’ve been giving this some thought lately and developed a couple ideas of how to add these features into a wordpress site without too much difficulty. A bulb went off in a moment clarity when I started to think about using the Custom Fields to store page specific metadata. I was even naive enough to think I was on to something new (should have known better) but as I started researching some ideas, I realized there were others already doing similar things. Oh well, a minor detail. I took my own approach to the idea anyway, if for no other reason than a learning exercise. Ultimately, this could be added as a premium feature to any custom theme using a couple hooks and some custom theme options magic.

Okay smarty-pants! So how do we include description and keyword metadata?

The solution isn’t difficult to implement and can be used to add page specific metadata inside the <head> tag of any wordpress page. In this example, I’m going to show you a simple solution, but with some creativity and a little thought, you can expand this to provide a more robust solution for your own needs.

Part I: Defining a Custom “Keywords” Field

Custom Fields are a little used gem found in the Posts and Pages page of the WordPress dashboard / admin back end and available when you add a new post or page, or edit an existing post or page.

Create a new custom field

Create a new custom field

To create a new custom field to use for your page or post keywords, scroll down to the Custom Fields section below the main editor and click the “Enter new” link.

That action will activate the input fields for “Name” and “Value”.

In the Name field type the name identifier you’d like to use. This identifier/name will be used to reference the custom field name/value pair later so make it something relevant to avoid confusion. For this example, I am using “keywords“.

In the Value field, type the string of keywords or phrases that you want to use as the keyword metadata string for the page/post. For this example, I am using wordpress, seo, metadata, custom fields

Add New Custom Field Inputs

When you’re done, hit the “Add Custom Field” button.

If you have already created a “keywords” Custom Field for a previous page or post, you will have the option of selecting it in future pages and posts from the Name drop down menu.

Custom Fields Menu

Select from Custom Fields Menu

Select the Keywords item from the menu and then add the keywords or phrases for your new page to the Value field. When your done, make sure you hit the “Add Custom Field” button to confirm it.

That completes Part I. You now have a functional Custom Field assigned to your post/page.

Next up! Adding and understanding the code that generates the keyword metadata tag.

Part II: The Magic Code.

function set_keywords(){
global $post;
$keywords = get_post_meta($post->ID, ‘keywords’, true);
$default_keywords = “Your, selection, of, default, keywords”;
$metatag= “”;

if (empty($keywords)){
$keywords = $default_keywords;
}
if (is_home() || is_front_page()){
$keywords = $default_keywords;
}

$metatag=”\t”;
$metatag.= “<meta name=\”keywords\” content=\””;
$metatag.= $keywords;
$metatag.= “\” />”;
$metatag.= “\n\n”;

echo $metatag;
}
add_action(‘wp_head’, ‘set_keywords’);

Adding this block of code to your Theme’s functions.php file will create and insert page specific Keyword Metadata into inside the <head> tag of your pages and posts assuming you have completed Part I.

How the code works

function set_keywords(){

The first line declares our function and sets the name “set_keywords”.

global $post;
$keywords = get_post_meta($post->ID, ‘keywords’, true);
$default_keywords = “Your, selection, of, default, keywords”;
$metatag= “”;

These four lines set up the variables that will be used later in the function.

global $post allows the function to reference values stored in an array containing post information that was previously set by WordPress outside of the current function.

$keywords = get_post_meta($post->ID, ‘keywords’, true) is up next and sets our variable, $keywords to a string value equal to the “keywordsCustom Variable if it was set for the current page in Part I by calling the wordpress function get_post_meta().

get_post_meta() is passed three arguments.

  1. The post ID ($post->ID)
  2. a Custom Field Name reference (keywords)
  3. a boolean value (true)

These three arguments tell get_post_meta() to grab the “keywords” Custom Field value for a specific page ($post_ID = a reference to the current page) and return a string result (true).

Note: If the Boolean argument were set to “false”, get_post_meta() would return an array object instead of a single string.

$default_keywords = “Your, selection, of, default, keywords” sets a set of default keywords to use when the $keywords variable is empty or not set, or when you just want to include a general set of keywords.

$metatag = “” rounds up the variables for the function and is used to build the metadata tag string that will be inserted into the page <head> tag.

if (empty($keywords)){
$keywords = $default_keywords;
}

The next step in the code is a conditional statement. Here I use the common PHP empty() function passing the $keywords variable as an argument to check whether the $keywords variable contains a value. If the empty() function returns true it means that $keywords does not contain a usable value, or that is has not been set. If this condition is true, it will set the value of $keywords to that of $default_keywords.

If the Keywords Custom Field was set for the current page, then the get_post_meta() function should have set the $keywords variable to a usable value equal to the Keyword Custom Field value. The condition will return false and the variable retains it’s Custom Field value.

if (is_home() || is_front_page()){
$keywords = $default_keywords;
}

Next I have another conditional statement that uses WordPress functions  to see if the current page is either the home page – is_home(),  or the “blog” page – is_front_page() If the current page matches either of these pages, I want to assign the value of $default_keywords to the $keywords variable.

The reason I do this is because the content on these pages is more dynamic and has a tendency to change often, effecting keyword relevancy. So I want to provide a generic set of default keywords instead of page content specific keywords.

Note: It is possible, using more in-depth techniques not covered here, to also include the Keywords Custom Field for these pages and enable a set of more targeted keywords for them.

$metatag=”\t”;
$metatag.= “<meta name=\”keywords\” content=\””;
$metatag.= $keywords;
$metatag.= “\” />”;
$metatag.= “\n\n”;

These lines are used to build the actual text string creating the metadata tag for our page’s <head> tag.  for example, if our page contained a keyword Custom Field with a value of  “keyword1, keyword2, keyword3”, the output for a blog post or single page would be:

<meta name=”keywords” content=”keyword1, keyword2, keyword3″ />

echo $metatag;
}

Wrapping up the function we have echo $metatag followed by the closing bracket bringing our function to a close.  echo $metatag simply writes the output of the $metatag variable to the source of your web page inserting the keyword meta tag in the page’s <head> tag.

add_action(‘wp_head’, ‘set_keywords’);

And finally bringing this code bit to an end is add_action(‘wp_head’, ‘set_keywords’). The add_action() function is a wordpress function used to hook your custom function to a WordPress action. In this case we are hooking our function set_keywords to the wordpress action wp_head. This is the piece that actually inserts your meta tag into the page <head> tag.

Note: It is up to the individual theme developers to include the wp_head action in their themes, so there is a chance that your theme will not have it. In that case, check the documentation for your theme to see what action hooks are available to you.

That pretty much wraps it up!

Umm, Aren’t you forgetting something?

By now you may be thinking, “Great, but what about the Description meta tag you mentioned?”.

You can use this same technique demonstrated here to create unique page descriptions with just a few minor code changes. Just replace keyword references with description references.

Do you have any suggestions to imporve on this? Find it helpful? Have some else to share? Leave a comment!

12 Responses to “WordPress: Use Custom Fields To Add Keyword Metadata to Your Posts”

  1. Ed Stafford

    Hi Zia.
    Thanks for reading the post. You didn’t give very much information as to the details of the problem, so I’ll throw out a couple thoughts. I have this code running on a number of blogs, personal and client, and it works great. You say “not showing in my post”. That’s because this is for Meta Keywords that are added to the the HTML header section of the page used for search engines and web crawlers. SEO rules recommend using unique meta keywords that are specific to the content of each page for best results. They will not be visible “in your post”. You need to check the “head” section/tag in the source of a rendered page to see the output.

    Example:

    head
    meta name=”keywords” content=”SEO, keywords, HTML” /
    /head

    Note: html <> brackets removed. WordPress kills HTML code in comments.

    If you are referring to the source and the meta keyword tags are not being added to the html head, then make sure the theme you are using calls the wp_head action. As noted above in the post, not all theme developers include this in their custom themes. My code depends on and is injected into the wp_head action so if wp_head is not being called in your theme, my code will not work.

  2. Ashley Lojko

    Wow this was SUPER helpful. I’ve been banging my head against my desk trying to figure out how I can add this data for each page. Since wordpress doesn’t function like a typical site, it was hard to wrap my head around. Now my life is way easier. Thanks for posting this info!

  3. Christy

    Hi. By far, this is the most user-friendly tutorial on this subject! Literally, I have spent the past five hours reading everything I can on inserting keywords and descriptions into the head of my site. Half of the commentary out there I can’t understand and the other half hasn’t worked! I created the custom fields and would like to insert this code as you instructed above. Where exactly in functions.php should this be inserted? Thank you for your help.

  4. hitokirihoshi

    hi! i thank you for sharing this info that i’m trying to figure out for days. i can follow the custom field part. but do i have to do something about part 2?

  5. admin

    @hitokirihoshi
    Yikes, late reply. To answer your question, for part II, you only need to insert the that block of code / function into your theme’s “functions.php” file. That should be all that is needed if you followed along with the instructions. I hope that helps and thanks for reading.

  6. Lyn Dwyer

    Hello, I have a list of meta data with article title, author, link, summary in excel file and how I add this information into wordpress site meta tags without doing data entries so that it supports SEO and users can search and results display on our site, when users click on link, it takes them to where the article is located. I would appreciate you point me to a good direction to accomplish this.

  7. Nikolai

    Thanks for thist post! I fell very good after custum adding seo meta elements.

  8. Mario Cisneros

    Ed,

    3-years after you posted this very useful tutorial it’s still incredibly relevant today. I’ve been working with WordPress on and off for 5-years, and although I knew the functions.php file was the place to start, I didn’t know where to find the “Magic Code” that would generate the meta data.

    My sincere gratitude for taking the time to provide this information!

    Respectfully,
    Mario

  9. admin

    Mario,
    Thank you for the comment. I am happy you were able to make use of the information here; even 3 years later.
    Happy coding!