Publish: 2017-06-21 | Modify: 2017-06-21
Some WordPress themes do not consider SEO optimization during development. It is not wise to manually set article keywords and descriptions. Of course, you can use plugins to help you, such as All in one seo. However, WordPress has a principle of using code instead of plugins as much as possible to avoid excessive resource consumption and impact on site speed.
Modify the functions.php
file in the theme directory and add the following code. Note that you need to modify line 43 and line 44 to your own website's keywords and description. After adding the code, the plugin will automatically retrieve the article tags as keywords and the first 200 words of the article as the description.
// Automatic keywords and description
function meta_SEO() {
global $post;
$output = '';
if (is_single()) { // If it is a single article page
$keywords = '';
$description = '';
if ($post->post_excerpt) { // If the article excerpt exists, use it as the description
$description = $post->post_excerpt;
$description = str_replace("\r\n", "", $description);
$description = str_replace("\n", "", $description);
$description = str_replace("\"", "'", $description);
$description .= '...';
} else { // If the article excerpt does not exist, truncate the first 200 words of the article as the description
$description = utf8Substr(strip_tags($post->post_content), 0, 200);
$description = str_replace("\r\n", "", $description);
$description = str_replace("\n", "", $description);
$description = str_replace("\"", "'", $description);
$description .= '...';
}
$tags = wp_get_post_tags($post->ID); // Get article tags
foreach ($tags as $tag) {
$keywordarray[] = $tag->name;
}
// Use article tags as keywords
$keywords = implode(',', array_unique((array)$keywordarray));
} else if (is_category()) {
$description = strip_tags(trim(category_description()));
$keywords = single_cat_title('', false);
} else { // If it is not a single article page or category page
$keywords = 'WordPress, wordpress themes, WordPress plugins, WordPress development, code, front-end, website building'; // Enter your blog's keywords between the quotes, separated by commas
$description = 'A personal blog about WordPress tips and front-end development knowledge, focusing on sharing, researching, and discussing WordPress tips. The author is a WordPress geek.'; // Enter a brief description of your blog between the quotes, no more than 200 words
}
// Output keywords
$output .= '<meta name="keywords" content="' . $keywords . '" />' . "\n";
$output .= '<meta name="description" content="' . $description . '" />' . "\n";
// Output description
echo "$output";
}
This article refers to: Code Implementation of Automatic Keywords and Description in WordPress
I come from China and I am a freelancer. I specialize in Linux operations, PHP, Golang, and front-end development. I have developed open-source projects such as Zdir, ImgURL, CCAA, and OneNav.