I’ve stripped Private:
and Protected:
from my custom post title that are forced to be private. I’m using CSS Tricks’ snippet for doing so:
function the_title_trim($title) {
if( is_admin() )
return $title;
$title = esc_attr($title);
$findthese = array(
'#Protected:#',
'#Private:#'
);
$replacewith = array(
'', // What to replace "Protected:" with
'' // What to replace "Private:" with
);
global $post;
if( 'mycpt' === get_post_type($post) ) {
$title = preg_replace( $findthese, $replacewith, $title );
}
return $title;
}
add_filter('the_title', 'the_title_trim');
It works fine as expected.
But recently when I switched to a different language, I found it’s not working. And you can guess easily that, the $findthese
array is failing to match any other language’s strings for those specified.
How can I use preg_replace()
for stripping the texts, that supports i18n strings?
1 Answer
We can use the protected_title_format
and private_title_format
filters, available since WordPress version 2.8:
add_filter( 'protected_title_format', 'wpse_pure_title', 10, 2 );
add_filter( 'private_title_format', 'wpse_pure_title', 10, 2 );
function wpse_pure_title( $format, \WP_Post $post )
{
return 'mycpt' === get_post_type( $post ) ? '%s' : $format;
}
to get rid of the “Private:” and “Protected:” parts on the front-end for the mycpt
post type.
We don’t need a is_admin()
check here, because these filters only run in the front-end.