Creating Private Categories

Since you've already seen so many examples of actions, I'll show you just one more. The function in Listing 9-22 creates private categories using the save_post() action, which occurs on the Edit ^ Post page after the new or updated post has been saved to the database.

Listing 9-22. Creating private categories function set_private_categories($postid) {

$postid = $parent_id; $privatecats = get_option('private_categories'); // array of category IDs if (!is_array($privatecats))

$privatecats = array($privatecats); foreach ($privatecats as $cat) {

if (in_category($cat, $postid)) { $updated = array(); $updated['ID'] = $postid; $updated['post_status'] = 'private'; wp_update_post($updated);

add_action('save_post', 'set_private_categories');

In this function, you'll assume that there's an option stored somewhere containing the IDs of the categories that should be private. (This function is part of my Private Suite plugin, and there, the private categories are part of the plugin's options array.)

The very first thing to do is see if you're saving a revision—that is, if this is happening during an autosave. If so, you really want the ID of the revision's parent—the current revision—rather than the revision ID.

Next, you'll get the array of category IDs. If it isn't an array for some reason, you'll make it one. Then, for each private category in the array, you'll check to see if this post has been assigned to that category. If it has, you need to change the post status. The wp_update_post() function requires an array containing the post's ID and any fields that need to be updated, so your array has just two elements.

To use this code example on your site, you might want to combine it with the examples in Chapter 10 on choosing which roles may read private posts. Otherwise, just like your editorial comment shortcode, the content in these categories will be limited to editors and administrators.

0 0

Post a comment