How to correctly get post type in a the_title filter

I want to prepend text to the post titles of a specific custom post type, but the filter below didn’t work. Instead of changing only that CPT’s post titles, it changed all titles on the given CPT’s pages—menus items, posts in secondary loops, etc.

What am I doing wrong? I’m guessing it’s something to do with the scope of get_post_type().

add_filter( 'the_title', 'add_cpt_prefix' );

function add_cpt_prefix( $title ) {
    if ( get_post_type() == 'press' ) {
        $title="<span>Press:</span> " . $title;
    }
    return $title;
}

4 Answers
4

You can exclude menus by testing the post id :

add_filter( 'the_title', 'add_cpt_prefix' );

function add_cpt_prefix( $title ) {
    global $id, $post;
    if ( $id && $post && $post->post_type == 'press' ) {
        $title="<span>Press:</span> " . $title;
    }
    return $title;
}

Leave a Comment