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
1 Answer
Reset to default 1Your "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()