Code your own SEO function with WordPress: the keywords

This is the third and last post of our SEO serie. After title, meta robots, and description, we will study meta keywords.

Objectives

We still want to fill automatically,the field meta keywords. The word automatically is important for me, because I think it’s a real added value, of a SEO function. Automatic generation saves significant time.

Possible approaches

To fill the field meta keyword, I found three ways:

  • Use an existing plugin, such as Simple Tags,
  • Request to users to give the keywords during the post editing,
  • Build a keywords list, from existing information (post content, tags, category …).

The first way is easy, because we don’t need to develop anything 🙂 .
But this post is speaking about development and coding, then we will discuss about the third way. The second doesn’t interest us, because it’s manual.

Main structure

We keep the structure started in the previous post, and we only add a new function for keywords:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
add_action('wp_head', 'my_seo_features', 1);
 
function my_seo_title() {
   // Fonctions affichant le titre
}
 
function my_seo_description() {
   // fonctions affichant le champ description
}
 
function my_seo_keywords() {
   // fonctions affichant le champ keywords
}
 
function my_seo_features() {
	my_seo_title();
	my_seo_description();
	my_seo_keywords();
}

How to build the field Keywords

We do the same exercise than the previous post. We have to

  • Define what we want to display,
  • Look at available informations.

The short study give us the following table:

Page type Available informations
(*)
Keywords
1. Home page List of posts Tags attached to the posts
2. Post or page Title, post/page content Tags attached to the post
3. Category Name and description of the category, list of posts Name of the category, tags attached to the posts
4. Tags Tags themselves, list of posts Tag name, tags attached to the posts
5. Search Search query, list of posts Tags attached to the posts
6. Archives Date, list of posts Tags attached to the posts

(*) information directly accessibles.

The conclusion is easy: we cannot build the field meta keywords with the directly available information. We need to query the database.

Overall, if we are displaying a post, we just have to get tags of the post. In the case of a list of posts, we have to get all tags linked to posts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function MOT_seo_keywords () {
  global $posts, $wpdb;
 
  if ( is_single() ) {
      $page_keywords = get_the_tag_list('', ' ', '');
  }
  elseif (is_home() || is_category() || is_tag() || is_date() || is_search() ) {
	foreach ($posts as $post_values) {
		$array_id[] = $post_values->ID;
	}
	$list_id = implode('","', $array_id);
	$sql_query = 'SELECT DISTINCT name	'.
                    'FROM '.$wpdb->term_relationships.' AS rel,'.
                            $wpdb->term_taxonomy.' AS tax,'.
                            $wpdb->terms.' AS ter '.
                    'WHERE tax. taxonomy = "post_tag" '.
                    'AND rel.object_id IN ("'. $list_id.'") '.
                    'AND rel.term_taxonomy_id = tax.term_taxonomy_id '.
                    'AND tax.term_id = ter.term_id ORDER BY tax.count';
	$results = $wpdb->get_results($sql_query);
	$page_keywords = implode(' ', $results);
  }
  if ($page_keywords != '') {
      $page_keywords = htmlspecialchars(stripslashes(strip_tags(str_replace("n", '', $page_keywords))));
      echo ''."n";
  }
}

Some explanations:

  • In line 5, we are displaying a single post: we can use the WordPress function get_the_tag_list to get tags,
  • From line 7, we process other cases,
  • In line 9, we get the ID of all displayed posts,
  • In line 12, we build the query to get the tags linked to displayed posts,
  • In line 20, we request the database,
  • In line 21, we translate the resulting array to a string.

Two comments about this function:

  • Using directly the global variable $posts is not perhaps the best way. I use it to avoid to query database,
  • Perhaps also the query isn’t well optimized. Use WHERE ... IN can generate a big workload for the database,

In the two cases, you can read the WordPress documentation or read the code of plugins such as Simple Tags.

You will find the code of this post here:


SEO: title, description and keywords
Titre: SEO: title, description and keywords (226 clics)
Légende: SEO: title, description and keywords
Nom du fichier: my_seo_features_21.txt
Taille: 4 KB

Some improvements

This function provides us quite good results, except for the case of a single post. If this post has only one or two tags, the field meta keywords will contain only one or two items.
Two possible ways:

  • Use data filled by users (with custom fields for example),
  • Build keywords using the post content (experimental)

In the first case, the solution is simple: we replace or append the result of the function get_the_tag_list with the content of a custom field that can be named keywords for example.

1
2
3
4
5
6
if ( is_single() ) {
    global $post;
    $page_keywords = get_the_tag_list('', ' ', '');
    $user_keywords = get_post_meta($post->ID, 'keywords', TRUE);
    if ($user_keywords != '') $page_keywords .= $user_keywords;
}

The author of posts will have to fill the custom field keywords, if he wants to append the list automatically generated.

The second way is more complex, but stay simple, with the array processing functions of PHP:

1
2
3
4
5
6
7
8
9
10
11
if ( is_single() ) {
  // Get tags of the current post
  $page_keywords = get_the_tag_list('', ' ', '');
 
  // Split Excerpt or content into words and store them in an array
  if ($post->post_excerpt != '') $words = split(' ',strip_tags($post->post_excerpt));
  else $words = split(' ',strip_tags($post->post_content));
 
  // Suppress all words < 5 chars
  $words_size = sizeof($words);
  for ($i=0; $i

Some explanations:

  • First, we get text from post (lines 6 and 7),
  • Then we transform this text into an array of words,
  • In line 12, we suppress the words of less than 5 characters,
  • The PHP function array_count_values allows us to calculate how many time each word is repeated. The result is an array, with words, and the number of time they appear.
  • We just have to sort the resulting array (line 18) to get the most used words, at the top of the array
  • We take only the first 10 words in line 21.

This method is, of course, an approximation. When we filter the words of less than 5 characters, we filter also keywords such as … SEO for example. So this method can be improved with a list of exception. But the results are sometime quite surprising. This method is already used by some SEO plugins.

Conclusion

This post is the last of the serie about coding SEO functions. This post was, at the end, more complex than I planned initially.
Despite everything, you can notice that the development of such functions is not so difficult. This small code can avoid to install some heavy (too heavy) plugins. If you have a big blog, with a lot of activity, several authors, … perhaps the best solution is to use an existing plugin. But in the other case, this « manual » solution can be a good compromise.

Personally, I use my own functions to build the title and description fields. For the keywords, I trust the plugin Simple Tags.

Autres articles de cette série

  1. Code your own SEO function with WordPress: the keywords (19 février 2009)
  2. Développer vos propres fonctions SEO avec WordPress: les mots-clés (19 février 2009)
  3. Develop your own SEO features with WordPress: the description (12 février 2009)
  4. Développer ses propres fonctions SEO avec WordPress: la description (12 février 2009)
  5. Develop your own SEO functions with WordPress: the title (5 février 2009)
  6. Développez vos propres fonctions SEO avec WordPress: le titre (5 février 2009)
  7. 6 plugins SEO pour WordPress (5 janvier 2009)