We’re all excited about the new features in Automattic’s P2 Theme v1.4.0 – however many of us have setup custom tweaks around Post Categories. In the latest version these have been replaced with Post Formats.
Post Formats are great, but they are limited to values defined in the WordPress core. If you wanted to create a new post menu like “critical” or “alarm” this wouldn’t work. We could use Custom Post Types to add to those formats, however it’s way too big an operation for I wanted to achieve: which is bringing back the “posting into categories” feature we’ve come to love from the previous version.
In this article I’ll show you how to back-port categories so posts will appear as they did in P2 v1.3.3 while retaining all functions of the latest update.
I’ve explained how to tweak labels for the post menu in an earlier post – instructions for adding and amending labels are still the same. Here we’ll delve right in to adding a few statements to the P2 code.
Let’s focus our attention on /inc/ajax.php file which contains our function that creates a new post (line 191). We’ll leave everything intact here. Have a look at this array first:
$post_id = wp_insert_post( array( 'post_author' => $user_id, 'post_title' => $post_title, 'post_content' => $post_content, 'post_type' => 'post', 'tags_input' => $tags, 'post_status' => 'publish' ) );
What’s missing here is a category definition so let’s add one to the bottom:
$post_id = wp_insert_post( array( 'post_author' => $user_id, 'post_title' => $post_title, 'post_content' => $post_content, 'post_type' => 'post', 'tags_input' => $tags, 'post_status' => 'publish', // bringing back P2 categories 'post_category' => array( $post_cat->cat_ID ) // ) );
This is pretty much what P2 v1.3.3 did. Just above this block we need to grab the post format and set it as our category, then convert the category slug to a numeric value so that we can use it in this array. Only takes two lines of code (one if you make it more complex) – put them just above the array block:
// define $post_cat $post_cat = $_POST['post_format']; // and turn it into the category ID $post_cat = get_category_by_slug( $post_cat );
Now P2 will look at the Post Format (say ‘status’) and add your post to a category with the same name. If your category does not exist then the post will appear in your default category as defined under Settings – Writing.
Here are some screenshots to illustrate the benefits:
This tweak will give you everything the new and improved P2 has to offer while still giving you access to all your category amendments and queries.
This is a re-blog of my original article – if you have comments or questions, please head over there and keep things in one place.