Remove "Private" + ":" in title does not work

I would like to remove the "private" prefix for each post title. I found the filter here. I managed to removed the word "Private" but when I concatenate with " : ". That does not work anymore. I checked $title value before the str_replace and it´s already translated with " : ".

Class FrontEnd{

    protected function front_end_init() {
        add_filter( 'the_title', array( $this, 'remove_private_prefix' ) );
    }

    public static function remove_private_prefix( $title ) {
        $title = str_replace( __( 'Private' ) . " : ", '', $title);
        return $title;
    }
}

How can I fix this ?

Topic get-the-title filters Wordpress

Category Web


Try removing the space before the colon, so " : " becomes ": ". Or use a superior method like shea's.


The simplest answer is as follows:

add_filter( 'private_title_format', function ( $format ) {
    return '%s';
} );

It uses the private_title_format to change the format of the title to just the post title, without any unnecessary classes or functions.


As @Sally CJ said, A better way is to used the function private_title_format. So...

If you can set the WP_Post, you can use this code line :

apply_filters( 'private_title_format', "", $post );

If you do not know the $post for some reason like for my example, you can overwrite the filter like this:

Class FrontEnd{

    protected function front_end_init() {
        add_filter( 'private_title_format', array( $this, 'remove_prefix_private_post_title' ), 10, 2 );
    }

   public function remove_prefix_private_post_title( $format, $post ){
        return '%s';
   }
}

I found a solution based on this post

Class FrontEnd{

    protected function front_end_init() {
        add_filter( 'the_title', array( $this, 'remove_title_prefix' ) );
    }

    public static function remove_title_prefix( $title ) {
        $title = esc_attr($title);

        $findthese = array(
            '#['  . __("Protected") . ' : ]#',
            '#[' . __("Private") . ' : ]#'
        );
        $replacewith = array(
            '', // What to replace "Protected:" with
            '' // What to replace "Private:" with
        );

        $title = preg_replace($findthese, $replacewith, $title);
        return $title;
    }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.