Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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;
}
share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

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;
}
share|improve this answer
    
Checking for $id does the trick. –  supertrue Mar 14 '12 at 4:16
add comment

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}";
}
share|improve this answer
    
2 more edits and it is a communtiy wiki ;) –  kaiser Aug 17 '11 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 '11 at 9:43
1  
then use the add_filter just before your loop, and add remove_filter after the loop –  Bainternet Aug 17 '11 at 9:55
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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