wordpress自定义设置SEO标题、关键词和描述,把如下代码放到模板目录functions.php里即可:
/**
* 设置SEO标题
* @author albert
* @date 2021-06-21
*/
function wp_seo_title() {
global $s, $post;
$category = get_the_category();//默认获取当前所属分类
$seo_title = get_term_meta($category[0]->cat_ID, 'category_seo_title', true );
echo $seo_title;
}
/**
* 设置关键词
* @author albert
* @date 2021-06-02
*/
function wp_keywords() {
global $s, $post;
$keywords = '';
if (is_single ()) { //如果是文章页,关键词则是:标签+分类ID
if (get_the_tags ( $post->ID )) {
foreach ( get_the_tags ( $post->ID ) as $tag )
$keywords .= $tag->name . ', ';
}
foreach ( get_the_category ( $post->ID ) as $category )
$keywords .= $category->cat_name . ', ';
$keywords = substr_replace ( $keywords, '', - 2 );
} elseif (is_home ()) {
$keywords = ''; //主页关键词设置,自己设置
} elseif (is_tag ()) { //标签页关键词设置
$keywords = single_tag_title ( '', false );
} elseif (is_category ()) {//分类页关键词设置
$category = get_the_category();//默认获取当前所属分类
$keywords = get_term_meta($category[0]->cat_ID, 'category_seo_keywords', true );
// $keywords = single_cat_title ( '', false );
} elseif (is_search ()) {//搜索页关键词设置
$keywords = esc_html ( $s, 1 );
} else {//默认页关键词设置
$keywords = trim ( wp_title ( '', false ) );
}
if ($keywords) { //输出关键词
echo $keywords;
}
}
/**
* 设置描述
* @author albert
* @date 2021-06-02
*/
function wp_description() {
global $s, $post;
$description = '';
$blog_name = get_bloginfo ( 'name' );
if (is_singular ()) { //文章页如果存在描述字段,则显示描述,否则截取文章内容
if (! empty ( $post->post_excerpt )) {
$text = $post->post_excerpt;
} else {
$text = $post->post_content;
}
$description = trim ( str_replace ( array (
"rn",
"r",
"n",
" ",
" "
), " ", str_replace ( "", "'", strip_tags ( $text ) ) ) );
if (! ($description))
$description = $blog_name . "-" . trim ( wp_title ( '', false ) );
} elseif (is_home ()) {//首页显示描述设置
$description = get_bloginfo ( 'description' ); // 首页要显示的描述,首頁要自己加
} elseif (is_tag ()) {//标签页显示描述设置
$description = $blog_name . "about '" . single_tag_title ( '', false ) . "' articles";
} elseif (is_category ()) {//分类页显示描述设置
$category = get_the_category();//默认获取当前所属分类
$description = get_term_meta($category[0]->cat_ID, 'category_seo_des', true );
// $description = $blog_name . "about '" . single_cat_title ( '', false ) . "' articles";
} elseif (is_archive ()) {//文档页显示描述设置
$description = $blog_name . "in: '" . trim ( wp_title ( '', false ) ) . "' articles";
} elseif (is_search ()) {//搜索页显示描述设置
$description = $blog_name . ": '" . esc_html ( $s, 1 ) . "' result";
} else {//默认其他页显示描述设置
$description = $blog_name . " about '" . trim ( wp_title ( '', false ) ) . "' articles";
}
//输出描述
$description = mb_substr ( $description, 0, 220, 'utf-8' );
echo $description;
}
add_action ( 'wp_head', 'wp_keywords' ); // 添加关键字
add_action ( 'wp_head', 'wp_description' ); // 添加页面描述