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

php - I need to add a filter to prepend the term 'National - ' to the post title if the post is tagged to multip

programmeradmin3浏览0评论

I am trying to add a filter to add the word "National - " to the beginning of the the post title if the post has multiple states that it is in.

Here is a screenshot:

I just figured out the add filter that adds the word "National - " to the beginning of the post title, but I can't figure out the if statement because I only need the word "National - to be added if the post has multiple states.

Here is the filter:

add_filter( 'the_title', function($title) { 
return 'National - ' . $title;
});

I am trying to add a filter to add the word "National - " to the beginning of the the post title if the post has multiple states that it is in.

Here is a screenshot:

I just figured out the add filter that adds the word "National - " to the beginning of the post title, but I can't figure out the if statement because I only need the word "National - to be added if the post has multiple states.

Here is the filter:

add_filter( 'the_title', function($title) { 
return 'National - ' . $title;
});
Share Improve this question edited Feb 26, 2022 at 22:23 Pat J 12.4k2 gold badges28 silver badges36 bronze badges asked Feb 25, 2022 at 13:57 user212573user212573 1
  • Why did you remove the text of your question? I'm going to restore it; the point of a Q&A site like this is to answer your question, as well as anyone else who might have a similar question. Removing the question once it's answered defeats the purpose. – Pat J Commented Feb 26, 2022 at 22:22
Add a comment  | 

1 Answer 1

Reset to default 1

Your "states" appear to be terms in a custom taxonomy. In the code below I've assumed the taxonomy's name is my_state; you'll need to make sure that's updated to match the actual taxonomy name.

add_filter( 'the_title', function( $title, $id ) {
    // Gets the list of 'states' the post belongs to.
    $states = wp_get_post_terms( $id, 'my_state' );
    // If there's more than 1 state, prepend 'National - ' to the title.
    if ( 1 < count( $states ) ) {
        $title = 'National - ' . $title;
    }
    return $title;
}, 10, 2 );

References

  • wp_get_post_terms()

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论