After studying the title tag, we are going now to look at the meta description tag.
This field is usually a brief summary of the page. Regarding search engines, the description has also to contain the main keywords to better classify the post.
Structure Overview
The general structure of the previous post was:
1 2 3 4 5 | add_action ( 'wp_head', 'my_seo_title'); function my_seo_title function () { // Function to print the title } |
We will now add a function to manage description. We take the opportunity to combine our SEO functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | add_action ( 'wp_head', 'my_seo_features', 1); function my_seo_title function () { // Function to display the title } function my_seo_description function () { // Function to display the description } function my_seo_features function () { my_seo_title (); my_seo_description (); } |
About add_action, we add the parameter ’1′. This parameter will put our function at the beginning of the list of actions to perform in wp_head(). In this way, our tags are located at the top of the header, rather than the bottom as in the previous post.
Generate description tag
Before starting, we have to define the content of this tag, for each case. For page ‘Category’, the answer is simple, since the categories have a description. But in the case of posts, archives, tags, what to do?
The following table summarizes what we can do:
| Page Type | Description |
|---|---|
| 1. Home | blog description |
| 2. Post or page | The excerpt of the post or the first few lines |
| 3. Category | The description of the category |
| 4. Tags | The summary of the first item of the list of posts |
| 5. Research | |
| 6. Archives | blog description |
Why these choices?
- Lines 1 and 3, we have a description, there is nothing to do
- Line 2, we can estimate that the summary of the post gives a good overview of the post itself,
- Lines 4 and 5, we can also consider that the posts corresponding to a tag or a search results, look more or less, similar. Therefore, the summary of the first article can be significant,
- Line 6 (archives), it seems difficult (even dangerous) to build a description based on several posts that can be very different.
How to collect information about the articles? Using global variables post and posts, which are generated by WordPress before loading pages.
We obtain the following PHP code:
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 28 29 30 | function my_seo_description() { global $post, $posts; if ( (is_single() || is_page()) ) { $page_description = get_description($post); } elseif (is_category()) { $page_description = category_description(); } elseif ( is_tag() ) { $page_description = get_description(current($posts[0])); } elseif (is_date()) { $page_description = get_bloginfo('description'); } elseif (is_search()) { if (sizeof($posts) > 0) { $page_description = get_description(current($posts[0])); } else { $page_description = get_bloginfo('description'); } } else { /* is_home normalement */ $page_description = get_bloginfo('description'); } if ($page_description != '') { $page_description = htmlspecialchars(stripslashes(strip_tags(str_replace("\n", '', $page_description)))); echo '<meta name="description" value="'.$page_description.'">'."\n"; } } |
Some explanations:
- Line 5: a single post is displayed, the global variable
$postis available, - Lines 11 and 18, we have a list of posts to display. The global variable
$postsis available. With the functioncurrent(), we get the first element (post), - In other cases, we retrieve the description of the blog,
- At the end, we try to filter as much as possible, the content of the description to avoid any incident during the display.
The get_description() can be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function get_description($current_post) { $max_length = 200; $string = ''; // If post has an excerpt? if ($current_post->post_excerpt != '') { $string = wp_html_excerpt ( $current_post->post_excerpt, $max_length); } else { // No excerpt, try to find the <!--more--> tag, or cut content. $char_count = min( $max_length, strpos($current_post->post_content, '<!--more-->')-1); // Extract description from the content $string = wp_html_excerpt ( $current_post->post_content, $char_count); } return ($string); } |
Some explanations:
- A description field must not exceed 100 to 200 characters (
$ max_length), - If the author has entered an excerpt, we use it,
- Otherwise, we retrieve the content of the post, we cut at the
<!--more-->, if it exists, or at most to 200 characters.
[attachment title="Download the complete code (including the sources of the previous post) from here:" titletag=p]
Conclusion
Our SEO Service is almost complete. We fill the fields title, robots meta, and description. We will see in a next post, how to fill in the meta keywords.
Other posts of the serie
- Développer vos propres fonctions SEO avec WordPress: les mots-clés - 19 February 2009
- Développer ses propres fonctions SEO avec WordPress: la description (This post) - 12 February 2009
- Développez vos propres fonctions SEO avec WordPress: le titre - 5 February 2009
- 6 plugins SEO pour WordPress - 5 January 2009
Français
Je sais. J’ai commence par cela, puis ne trouvant pas la bonne regex, je suis passe a la methode “simple”.
J’ai pourtant pratiquer les regex assez souvent qu’en j’etais admin unix, mais j’avoue avoir beaucoup perdu la main …
@Emmanuel : 2 strpos + 1 substr vs 1 preg_match. Les regex sont là pour ça !
Je te remercie vivement pour ta réponse mais le problème c’est qu’en php je n’y connais pas grand chose et du coup je sais pas trop ou coller ce code, j’ai tenté de le copier dans le fichier function.php et d’appeller la fonction dans mon header par la suite mais ça ne fonctionne pas je dois pas taper la bonne syntaxe…
Il suffit de faire une extraction du type:
Si je veux uniquement extraire de mon post ce qui est contenu entre ma balise h2 au lieu d’afficher les 170 premiers mot de mon post comme description, comme dans l’exemple si dessous, sais tu quel devra être alors la syntaxe php ?
“?php echo wp_html_excerpt($post->post_content, 170); ?”
Si je veux uniquement extraire de mon post ce qui est contenu entre ma balise au lieu d’afficher les 170 premiers mot de mon post comme description, comme dans l’exemple si dessous, sais tu quel devra être alors la syntaxe php ?
post_content, 170); ?>
Merci pour les félicitations que j’apprécie d’autant plus que je suis très fan de tes articles, pratiquement depuis que j’ai démarré mes petits travaux.
Concernant la fonction
get_description,$char_countest bien initialisé ligne 10. En ligne 13, je prends soit les 200 caractères de$max_length, soit le texte situé avant la balise.J’ai corrigé le fichier
my_seo_features_21.txtla ‘(‘ était effectivement en trop. Merci pour la remarque.En fait tu as été plutôt soft côté remarques: je viens de relire les articles, et ils étaient bourrés de coquilles: ‘(‘ en trop, lignes manquantes, mauvais numéros de ligne dans les explications … Je les ai sorti trop vite. En les relisant encore une ou deux fois je devrais atteindre un taux d’erreurs plus raisonnables…
Bonjour Emmanuel,
Félicitations pour ta série d’articles. J’ai utilisé tes fonctions pour mon blog. Je surveille le référencement mais je suis sûr que cela va résoudre mes problèmes de description trop courtes ou dupliquées sur certaines pages, notamment les pages de tag (merci google webmaster tools). Je préfère également utiliser des fonctions ou passer par du templating plutôt que d’utiliser un plugin usine à gaz. Ca laisse plus de contrôle.
Je te signale juste une erreur dans ton code de la fonction get_description : dans ton code; ligne 13, tu utilises la variable $char_count. Or celle-ci n’existe pas. Il faut reprendre la variable $max_lenght définie en haut de la fonction. Une petite erreur de nommage/ renommage
Par ailleurs, dnas la fonction my_seo_keywords dans le fichier que tu proposes en téléchargement (http://www.emmanuelgeorjon.com/images/2009/02/my_seo_features_21.txt) il y a nue ‘(‘ de trop ligne 94. Je te le signale, ça évitera à d’autres lecteurs d’avoir à chercher.
Pingback: Spirit of wordpress