How to correctly get post type in a the_title filter

The question:

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;
}

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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;
}

Method 2

You can globalize $post to work out the post type.

Example:

add_filter( 'the_title', 'add_the_title_prefix' );

function add_the_title_prefix( $title ) 
{
    global $post;
    if ( 'custom_post_type_name' != $post->post_type )
        return $title;

    return "<span>Press:</span> {$title}";
}

Method 3

In the years since this question has been added, the $id parameter has been added to the the_title action hook. So now you can get the post type easily using get_post_type() as so:

function actionTheTitle($title, $id)
{
    $post_type = get_post_type($id);

    // Clever code here

    return $title;
}

Method 4

The problem was not with get_post_type() like I thought, so Bainternet’s suggestion of $post->post_type produced the same results. Bainternet’s suggestion from the comments was what was needed:

use the add_filter just before your loop, and add remove_filter after the loop


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment