Automatically append a Word or Phrase after a Post Title, based on Category ID

This code is very simple. It adds a seperator (|) and a desired word or phrase at the end of a post, when it is in your defined category ID. For example, if you set the ID to 1, all posts in category ID 1 will have this text appended. You can see it in action, here.

Replace YOUR_ID_ONLY_NUMBER with the category ID (open your category’s edit page; the number in the URL is your category ID), and DESIRED WORD with your desired content.

function add_phrase_to_title( $title, $id ) {
    $categories = get_the_category( $id );
    foreach ( $categories as $category ) {
        if ( $category->cat_ID == YOUR_ID_ONLY_NUMBER ) {
            return $title . ' | DESIRED WORD';
        }
    }
    return $title;
}
add_filter( 'the_title', 'add_phrase_to_title', 10, 2 );

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *