1

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' ) );

2 Answers 2

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' ) );
1
  • 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
    Commented Jul 3, 2012 at 4:53
1

Maybe an easier way

if ( $post->post_type == 'custom_post_type' ) 

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.