Forums

Automatically Add Posts to A Category Conditionally (3 posts)

  1. adria
    Member
    Posted 9 months ago #

    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.

  2. adria
    Member
    Posted 9 months ago #

    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');
  3. adria
    Member
    Posted 9 months ago #

    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.

Reply

You must log in to post.

About this Topic