How to append text to title of Custom Post Type post (without affecting all titles on page)?

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.

Read More

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

Related posts

Leave a Reply

2 comments

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