• I have some code that successfully adds every new post (with publish_post action) to a specified category, excluding posts that are categorized with another specified category like so:

    function add_category_automatically($post_ID) {
    	global $wpdb;
    	if(!in_category('bundle')){
    		$cat = array(9547);
    		wp_set_object_terms($post_ID, $cat, 'category', true);
    	}
    }
    add_action('publish_post', 'add_category_automatically');

    This is working perfectly. I have another condition that I want to satisfy, which is to also exclude posts by a certain author from getting this category. I have the following code, but it is not working:

    function add_category_automatically($post_ID) {
    	global $post;
    	$author_id=$post->post_author;
    
    	$field='first_name';
    	the_author_meta($field, $author_id);
    	if ($author_id != 30) {
    		$cat = array(9547);
    		wp_set_object_terms($post_ID, $cat, 'category', true);
    	}
    
    }
    add_action('publish_post', 'add_category_automatically');

    I think it has something to do with when the author is assigned to the post, because if I uncheck the category 9547 that is automatically added with author_id 30 condition is met, then update the post, it stays gone. When author_id 30 condition is not met, then category 9547 stays checked, even if I uncheck it and update, it will just come back again.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter adria

    (@adria)

    ok I figured it out. here is what I wanted to do, and it now works:

    function add_category_automatically1($post_ID) {
    	global $wpdb;
    	$postsWeWants = $wpdb->get_results("SELECT ID, post_author FROM $wpdb->posts where ID = $post_ID");
    	foreach ($postsWeWants as $postsWeWant) {
    		if(($postsWeWant->post_author != 30) && ($postsWeWant->post_author != 29) && !in_category('bundle')){
    			$cat = array(9547);
    			wp_set_object_terms($post_ID, $cat, 'category', true);
    		}
    	}
    }
    add_action('publish_post', 'add_category_automatically1');
    Thread Starter adria

    (@adria)

    this function will automatically add all posts to category 9547, unless it is also in category bundle, or if the post is by author 29 or 30.

    Thank you for posting, asking the question, and then posting back with the answer you found. (I was looking for something that your first post answered). I see some some people don’t post when they found the answer…thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Automatically Add Posts to A Category Conditionally’ is closed to new replies.