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.

This question 'How to correctly get post type in a the_title filter' is exactly what I'm trying to achieve. I have set a filter as below but it affects all titles on the page (in the menu, sidebar and footer) rather than just the post title.

Apparently I need to use the add_filter just before the loop and add remove_filter after the loop, but I'm not sure how to do this. I'm developing a plugin and am looking for a solution that does not involve making any changes in theme/template files.

Love to hear any and all suggestions. Thanks

function custom_title( $title ) {
    global $post;
    $text = 'Extra text: ';

    if ( get_post_type( $post->ID ) == 'custom_post_type' ){
        return $text . $title;
    }
    else {
        return $title;
    }
}

add_filter( 'the_title', array($this, 'custom_title' ) );
share|improve this question

2 Answers 2

I believe checking in_the_loop will work for the main query:

function custom_title( $title ) {
    global $post;
    $text = 'Extra text: ';

    if ( get_post_type( $post->ID ) == 'custom_post_type' && in_the_loop() ){
        return $text . $title;
    }
    else {
        return $title;
    }
}

add_filter( 'the_title', array($this, 'custom_title' ) );
share|improve this answer
    
Thank you so much - that works beautifully! I've just added that second condition to the rest of my function and am very happy now :) –  k998 Jul 3 '12 at 4:53

Maybe an easier way

if ( $post->post_type == 'custom_post_type' ) 
share|improve this answer

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.