Develop your own SEO functions with WordPress: the title

February 5th, 2009

Some previous tests of SEO plugins, made me quite disappointed. However, they allowed me to explore the different methods used. These methods are simple and can easily be developed into a theme, for example.
This article is part of a series of three posts: the first (this one) will address the title and the robots meta tag, the second will speak about the description field and the last will be focused on keywords field.

Objective

We just want some functions to fill automatically the following tags:

  • Title
  • meta name="robots" content="..."
  • meta name="description" content="..."
  • meta name="keywords" content="..."

Functions must fit with different types of pages in WordPress.
I say automatically, because for me, the true added value of SEO functions is here. Automatic generation allows to save significant time.

Structure Overview

In this post and the followings, we will consider adding these features to a theme (the principle is the same for a plugin).

If your theme is developped properly, its header contains a call to wp_head () (in the HTML <head> and </head>.

We will change the behavior of wp_head() by adding our own functions (refer Hook in the documentation of WordPress).

Our php functions will have to

  1. Watch in what situation we are (page articles, archive page, homepage …),
  2. Collect available information,
  3. Format these information.

Point 1 is relatively easy through features available is_single(), is_page(), is_category()

Point 2 is a bit more difficult: we must no, as far as possible, overload our blog, with too many requests. We will have to collect existing information.

Point 3 is not so easy: we must be sure that the content will not generate an error.

To start, we open or create the functions.php in the root of the theme you are using. Then enter the following code:

add_action ( 'wp_head', 'my_seo_title');
function my_seo_title() {
   // Function to print the title
}

The my_seo_title() will contain everything you need to generate the title and robots meta properly.

Build the title and meta robots

The title that we want to build, will have the following structure: < string > | < blog title >

The meta tag robots is used to tell to search engines whether to scan the page, and / or follow the links it contains.

Here is the complete function:

function my_seo_title() {
  $separator  = '|';
  $blog_name  = get_bloginfo('name');
 
  if((!is_paged() ) &amp;&amp; ( is_single() || is_page() || is_home() || is_category())) $follow_content = 'index, follow';
  else $follow_content = 'noindex, follow, noodp, noydir';
 
  if ( (is_single() || is_page()) ) {
      $page_title = the_title('','', FALSE);
  }
  elseif (is_category()) {
      $page_title = 'Category: '.single_cat_title('', FALSE);
  }
  elseif ( is_tag() ) {
      $page_title  = 'Tag: '.single_tag_title('', FALSE);
  }
  elseif (is_date()) {
      $page_title = 'Post of ';
      if (is_day()) {
          $page_title .= get_the_time('j F Y', FALSE);
      }
      elseif (is_month()) {
          $page_title .= get_the_time('F Y', FALSE);
      }
      elseif (is_year()) {
          $page_title .= get_the_time('Y', FALSE);
      }
  }
  elseif (is_search()) {
       $page_title = 'Search results for: '.$_GET['s'];
  }
  if ($page_title != '') $page_title .= ' '.$separator.' ';
 $page_title .= $blog_name;
 
  echo ''."\n";
  echo ''."\n";
}

The source code is available here:

Title: my_seo_title
File: my_seo_title.txt
Size: 1 kB

In line 5 and 6, we tell to search engines what they have to do with the current page: For a page, a post or a category, we ask them to scan the content and follow the links. In all other cases, we ask them to do nothing.

From line 8, we try to know where we are, and build the title.
In line 32, if $page_title is empty, we could not find on which page we are.
If this variable is not empty, we will add a separator.

In line 33 we complete the title by the name of the blog.

Lines 34 and 35 ensure the display of tags. In line 34, we try to clean the title of any dangerous characters. This cleaning may also be made with WordPress features like sanitize_title().

Conclusion

We have now a theme with title, and robots meta for each of its pages.

As you can see, these functions are not really complex. In a few lines of code, we already obtain good results. We will see in a next post the case of the meta tag description.

Other posts of the serie

  1. Développer vos propres fonctions SEO avec WordPress: les mots-clés -
  2. Développer ses propres fonctions SEO avec WordPress: la description -
  3. Développez vos propres fonctions SEO avec WordPress: le titre (This post) -
  4. 6 plugins SEO pour WordPress -

Comments & trackbacks

Comments

6 responses

  1. Merci Emmanuel pour ces excellentes séries sur WordPress. ;)

  2. Merci pour les compliments.
    J’apprécie ton blog également. Il fait partie de mes abonnements depuis quelques mois. J’ai justement regardé la course de côte de Vatanen ce matin …


  3. Jean-Pierre

    Bonjour,

    Merci pour votre blog remarquable que je découvre en même temps que je m’initie au développement avec WordPress.

    J’ai beaucoup de lecture à faire.

    PS: Le premier lien du texte de l’article(“Les essais de plugins SEO”) pointe vers localhost/…..

  4. Merci pour les compliments.
    Erreur corrigée.

  5. Je viens de découvrir vos 3 posts consacrés aux fonctions SEO. D’emblée, l’idée géniale de remplacer un plugin lourd par quelques fonctions m’a enthousiasmée. De fait, après quelques aménagements personnels, j’utilise avec succès les fonctions my_seo_title()et my_seo_description().
    Toutefois, je rencontre un petit problème de typographie avec les données du type single_tag_title ou bien category_description qui ne supportent pas la présence d’apostrophe, systématiquement retranscrite en ”. Losqu’il s’agit d’un post_excerp, les apostrophes sont bien retranscrites.
    Après de vaines recherches, je me permets de vous soumettre mon problème. Je dois préciser que mon php est extrêmement extrêmement débutant…
    Y aurait-t-il une solution simple? remplacer l’apostrophe par son code ASCII ne change absolument rien malheureusement.
    Par avance merci de votre réponse.

  6. Bonjour,
    Il faut systematiquement utiliser les fonctions htmlspecialchars et stripslashes.
    Par exemple: htmlspecialchars(stripslashes(< texte a afficher >))

    Normalement avec ces deux fonctions, le texte affiche est “propre”, au sens HTML du terme.

Trackback / Pingback

2 trackbacks/pingbacks.

  1. Développez vos propres fonctions SEO avec WordPress: le titre…

    Les essais de plugins SEO réalisés précédemment, m’ont relativement déçu. Ils m’ont permis cependant d’étudier les différentes méthodes utilisées. Ces méthodes sont simples, et peuvent aisement être développées dans un thème, par e…

  2. [...] façon de bien gérer la balise H1 et de donner tout le poids SEO que cette balise peut apporter, – Développez vos propres fonctions SEO avec WordPress: le titre : une bonne façon d’optimiser sa balise title – certainement la balise la plus importante en [...]

Leave a comment