wordpress

WordPress: Take Control of Private Post Titles

WordPress gives us an easy built in way to hide certain posts or pages from non logged-in users, by simply marking the post status as private or password protected. When we do this, the title of the post or page will automatically be prefixed with “Private:” or “Protected:” In some cases this is no big deal, but sometimes we may want to prefix with something different, or nothing at all. Today we’ll see how we can take control of the matter.

WP Filters to the Rescue

To get in and have our way with the post or page titles, we’ll be using WordPress’s the_title filter. We’ll use the filter to insert a function which grabs the title of each post, checks explicitly for the text strings “Private”or “Protected”, and then replaces them with our own custom text strings (or nothing if we prefer.) PHP’s preg_replace function will get the job done quick and easy. Here’s what the snippet I usually start with looks like (Thanks to Chris Coyer at CSS Tricks for this one!):

function the_title_trim($title) {
    $title = attribute_escape($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;
}
add_filter('the_title', 'the_title_trim');

This snippet starts by getting rid of the prefixes altogether, but you can insert any text string you want into the $replacewith array. Just drop this into your theme’s functions.php file (or your plugin files, whatever the case may be) and that’s all there is to it!

Happy coding!

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *