2

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 ?

4

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.

1
  • Works perfectly whereas a few others I tried didn't. Thanks
    – TomC
    Oct 4 '20 at 10:56
0

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;
    }
}
2
  • 2
    I would use private_title_format - and protected_title_format for password-protected posts..
    – Sally CJ
    Aug 19 '19 at 14:34
  • 1
    The original problem was that you had a space before the colon: __( 'Private' ) . " : ",. Should just be __( 'Private' ) . ": ",. This is overkill. But using the correct filters would be the optimal solution. Aug 19 '19 at 14:40
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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