Automatically assign posts by author to a specific category

Some of the authors in my blog must always add their posts to a specific category each time they post.

Sometimes they forget this so therefore I’m wondering if there are any ways to automatically check and fix this.

Read More

Here’s an example of my desired outcome:

  • Posts by Author X should always be assigned to category A
  • Posts by Author Y should always be assigned to category B
  • Posts by Author Z should always be assigned to category C

How do I achieve this?

Related posts

Leave a Reply

5 comments

  1. The solution is quite simple. And is subdivided into two separate processes – querying the posts and modifying their category terms.

    Querying the posts

    get_posts is a function that returns posts. A full list of arguments can be seen in WP_Query parameters

    To get all posts for a specific author, you do something like:

    get_posts( 'numberposts=1&author_name=john' );
    

    Loop over each entry like so:

    foreach ( get_posts( 'author_name=john' ) as $post ) {
        // set categories...
    }
    

    Setting category terms

    wp_set_object_terms is the function you’ll be looking at and using.

    wp_set_object_terms( $post->ID, 'John's Category', 'category', false );
    

    Putting it together

    I would probably go for something like this:

    global $wpdb; // get the global db object
    
    foreach ( (array) $wpdb->get_results("SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_type = 'post' GROUP BY post_author") as $row ) {
    
        $author = get_userdata( $row->post_author ); // get all author data
    
        foreach ( get_posts( 'numberposts=-1&author='.$row->post_author ) as $post ) {
            switch ( $author->username ) {
                case 'joe':
                    $category = 'Joe's Entries';
                ...
            }
    
            // set categories
            wp_set_object_terms( $post->ID, $category, 'category', false );
        }
    }
    

    I’m sure there are ways in which you can further optimize this. Run this once to fix things. Then attach to save_post with just the set category part for future.

  2. I’m assuming you aren’t using custom post types. Below code successfully adds every new post (with publish_post action) to a specified category, excluding posts that are categorized with another specified category. You could simply tweak or remove the if statement to suit your specific needs.

    function add_category_automatically($post_ID) {
        global $wpdb;
        if(!in_category('specified-category')){
            $cat = array(9547);
            wp_set_object_terms($post_ID, $cat, 'category', true);
        }
    }
    add_action('publish_post', 'add_category_automatically');
    
  3. You’ll want to use the save_post hook, which is fired every time a post is saved or updated.

    The callback should (optionally) check if a category is set (ignoring ‘uncategorized’) and otherwise set the category according to author using a author ID to category slug array.

    The following is untested.

    function wpse45398_save($post_id,$post) {
         // verify this is not an auto save routine. 
         if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
    
         //You should check nonces and permissions here
    
         //Get category slugs associated with post
         $cats = wp_list_pluck(get_the_category($post_id),'slug');
         $cats = array_values($cats);
    
         //Remove 'uncategorised' from array
         unset($cats['uncategorised']);
    
         //If $cats array is empty
         if(empty($cats)):
           //Array of author ID to 'default category'
           $authorCat = array(
             '1'=>'mycatslug',
             '2'=>'myothercat',
             '3'=>'anothercat'
           );
           $author_id=intval($post->post_author);
           $defaultCat = isset($authorCat[$author_id]) ? $author_id : 0;
    
           if(!empty($defaultCat))
              wp_set_object_terms( $post_id, 'category', $defaultCat, true )
         endif;
    
         return;
    }
    add_action('save_post','wpse45398_save',10,2);
    

    See @Soulseekah’s answer if you want to ‘fix’ already existing posts – although this method will work by updating existing posts.

    The code above will ensure any future post is in at least one category (according to author)). Optionally, publish_post can be used to fire the callback function only when the post is saved and its status is publish, (thus for drafts the ‘correction’ won’t occur).

  4. You can set restrictions on individual users or roles too to post to a specific category using this plugin.

    Edit: It’s really easy to use the plugin, it might be worth the time to check the link out.
    However, i’ll still show you how to use it.

    After installing the plugin, you can go into Settings > Restrict Categories to access its settings.
    There you’ll see something like this:
    Restrict Categories settings screenshot

    As you can see, from here, you can decide which roles or users can post to which categories and stuff. When, say, you assign only the “University Update” category to the “Author” role, while posting a new post, the “Author” role users can only see the “University Update” category, i.e. the user can post only to that category. If you assign multiple categories, the the user can see multiple categories in the categories section while posting.
    I hope that explains pretty much all about how to use it.