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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments