Have you ever tried to create a category consisting entirely of private posts? It’s a pain to have to remember to set the visibility for each post before publishing it. One of my users simply couldn’t remember to do it, resulting in a lot of accidentally public posts on that site.
To solve the problem, I created this little function that catches posts as they’re being saved. It checks to see if the post is in the right categories, and if it’s being published — that is, it leaves draft, pending, and scheduled statuses alone. (It’ll automatically catch the scheduled posts when they go live.) If the post is being published, it gets set to private.
Here’s the code you can put in your theme’s functions.php
file:
//update_option('private_categories', array(79,34,75,73), ", 'yes'); add_action('save_post', 'set_private_categories'); function set_private_categories($postid) { global $wpdb; if ($parent_id = wp_is_post_revision($postid)) $postid = $parent_id; $privatecats = get_option('private_categories'); if (!is_array($privatecats)) $privatecats = array($privatecats); foreach ($privatecats as $cat) { if (in_category($cat, $postid)) { // wp_update_post() calls the save_post action again and could create an infinite loop, so we'll use the brute force method $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET `post_status` = %s WHERE ID = %d AND `post_status` = %s", 'private', (int)$postid, 'publish') ); } } }
For the sake of simplicity, I haven’t included the code you would need to create an option panel, although you could do so yourself if you like. (I’ll go over it in a later post.) To select your categories using this code alone, uncomment the first line (update_option
…). Replace the numbers in the array (79,34,75,73
) with the IDs of your private categories. Then view your site. You can view any post or page — on the public side, not from the dashboard — and functions.php
will execute, setting your option for you. Then comment out the line again (there’s no need to reset the option every time someone visits your site!) and save functions.php
. When you need to add a category, repeat this step.
The private category feature now included in the Private Suite plugin, which includes a number of things related to private and password-protected posts and pages.
Frank says
Is there any way to retroactively set all posts of a particular category to ‘private’? I know there’s bulk edit, but that only does one page of posts at a time. I have dozens of pages.
admin says
No, Frank, but I used the screen options tab to increase the number of posts per page to 100, so I had just a few pages to bulk edit.
Frank says
Thanks, that’s useful. I love the plug-in!
Jon says
Didn’t work for me, did nothing, until I un-commented the update, then it crashed my functions file..?