4

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

7

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;
}
2
  • Checking for $id does the trick.
    – supertrue
    Mar 14, 2012 at 4:16
  • Checking for $id only seems to work in some cases, not all. See @dotancohen's answer for a modern solution.
    – Ian
    Jan 17, 2023 at 11:03
7

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}";
}
3
  • 2 more edits and it is a communtiy wiki ;)
    – kaiser
    Aug 17, 2011 at 9:29
  • This causes all menu items on press posts to get "Press: " prepended. (The menu is a standard Wordpress menu.)
    – supertrue
    Aug 17, 2011 at 9:43
  • 1
    then use the add_filter just before your loop, and add remove_filter after the loop
    – Bainternet
    Aug 17, 2011 at 9:55
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;
}
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.