Generate the meta description automatically in WordPress

I believe many people don’t want to input the title, description and tags twice for SEO plugins while editing the posts in WordPress. It is better they can help us to generate the meta tags automatically, so that we can save time to have a cup of coffee. I’ve tried both “All in One SEO” and “SEO Ultimate”, they can generate title and keywords by existing title and tags. But both of them is not so smart and cannot generate meta description tag basing on the existing descriptions of posts, pages and tags. So we need write the program by ourselves.

In <head> tag of header.php, add below lines

<?php
// Generate meta description tag
if (is_home()) {
    $desc = "收罗了各种美丽的传说,也收录了我们不少旅行的见闻、力文的趣事以及一些管理和技术方面的笔记。
Collected various beautiful tales,also included some sees and hears during the travel all around the world, the fun of our son - Tony, and some technical & managerial notes while working and studying.";
} else if (is_single() || is_page()) {
    if ($post->post_excerpt) {
        $desc = $post->post_excerpt;
    } else {
        $desc = preg_replace("/\n|\r/", "", mb_strimwidth(strip_tags(apply_filters('the_content',$post->post_content)),0,220));
    }
} else if (is_category()) {
    $desc = preg_replace("/\n|\r/", "", strip_tags(category_description()));
} else if (is_tag()) {
    $desc = preg_replace("/\n|\r/", "", strip_tags(tag_description()));
}
?>

That’s it!

Some explains:

  • mb_strimwidth: Get truncated description with specified width.
  • strip-tags: Strip HTML and PHP tags from a description.
  • preg_replace(“/\n|\r/”, “”, …): Remove the new line characters in description.

One more thing, remember to disable the meta description generation feature of the SEO plugins, otherwise you will get the meta tag overwritten or duplicated.

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

Back to Top