Instantly Modify a Post’s Categories Using a WordPress Publish Post Hook

Scenario: Why I Needed to Learn WordPress Publish Post Hooks

I recently had the need to make all new blog posts become the sole occupant of the ‘featured’ blog category, and I much prefer groovy WordPress hook functions rather than scheduling a task on my calendar. The below function uses one of the more general WordPress publish post hooks, in that the function gets called more often but is then responsible for deciding if it should do things or not. As you will see, we are checking if the post is A) a regular ‘post’ and B) transitioning from an auto draft, future, or draft status to the published status. In case you need something more specific, there are multiple WordPress publish post hooks available for a wide array situations.

The Code

// Automatically make new posts the featured article in the blog
    add_action( 'transition_post_status', 'prefix_generic_post_status_transition', 10, 3 );
    function prefix_generic_post_status_transition( $new_status, $old_status, $post ) { 
        // This determines if the post is a fresh post
        if ( (($new_status == 'publish' && $old_status == 'auto-draft') || ($new_status == 'publish' && $old_status == 'future') || ($new_status == 'publish' && $old_status == 'draft')) && get_post_type($post->ID) == 'post'  ) {

            $featuredArticleArgs = array(
                'posts_per_page'   => 1,
                'offset'           => 0,
                'category_name'    => 'Featured',
                'post_type'        => 'post'
            );
            $featuredArticleArray = get_posts( $featuredArticleArgs );
            $previousFeaturedArticleID = (int)$featuredArticleArray[0]->ID;
            wp_remove_object_terms( $previousFeaturedArticleID, 'Featured', 'category' );
            wp_set_object_terms( $post->ID, 'Featured', 'category', true );
        }
    }

Closing Thoughts

As a side note, if you are utilizing this function in a custom WordPress plugin of your own, then my previous article about WordPress plugin development may be of use to you (I have to reference it often to get the proper markup, lol).

Leave a Reply

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