最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

headers - How to Customize Wp Default Title and a prefix

programmeradmin0浏览0评论

This code snippet shows (prefix) category Name first before the Post title (Very right).

E.g

  • Music: %Post_title%
  • Video: %post_title%
  • Lyrics: %post_title%
  • News: %post_title%
  • Lifstyle: %Post_title%.

Now the problem is, I wanted to show this on a very specific category(Music & Video) alone and not all categories...

E.g on category Music & Video alone.

Then any other post from any other category will not show any Prefix at all...

Below is the code snippet:

add_filter('wp_title', function ($title) {


if (is_single()) {
    $categories = get_the_category(get_the_ID());
    // Assuming the post has many categories will take the first
    $category = reset($categories);
    return $category->name .': '.$title; 
}
return $title;
}


);

This code snippet shows (prefix) category Name first before the Post title (Very right).

E.g

  • Music: %Post_title%
  • Video: %post_title%
  • Lyrics: %post_title%
  • News: %post_title%
  • Lifstyle: %Post_title%.

Now the problem is, I wanted to show this on a very specific category(Music & Video) alone and not all categories...

E.g on category Music & Video alone.

Then any other post from any other category will not show any Prefix at all...

Below is the code snippet:

add_filter('wp_title', function ($title) {


if (is_single()) {
    $categories = get_the_category(get_the_ID());
    // Assuming the post has many categories will take the first
    $category = reset($categories);
    return $category->name .': '.$title; 
}
return $title;
}


);
Share Improve this question edited Feb 20, 2020 at 21:35 Tom J Nowell 61.1k7 gold badges79 silver badges148 bronze badges asked Feb 20, 2020 at 21:22 Teejah JamesTeejah James 174 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Try this code.

add_filter('wp_title', 'custom_title');
function custom_title($title) {
    if(is_single()) {
        $category = get_the_category(get_the_ID());
        if(!empty($category)){
            $categories = array('music','video');
            if(in_array($category[0]->slug,$categories)){
                return $category[0]->name.': '.$title;
            }
        }
    }
    return $title;
}
发布评论

评论列表(0)

  1. 暂无评论