Search code examples
phpwordpresscategories

How to select a specific (WP) category in an if-statement in PHP?


I've been trying to make posts from a specific category private in wordpress (php) but I cannot seem to make it work.

I've tried this:

function force_type_private($post) {        
        if (get_the_category($post->ID) == [11]) { 
        $post['post_status'] = 'private';
  }
  return $post;
}

add_filter('wp_insert_post_data', 'force_type_private');

and this:

function force_type_private($post) {        
        if ($post['post_category'] == [11]) { 
        $post['post_status'] = 'private';
  }
  return $post;
}

add_filter('wp_insert_post_data', 'force_type_private');

...but it doesn't work. The problem is in the if-statement, without it all posts indeed turn to private.

All my posts have one (and only one) category. The category ID of the category I want to set to private is '11'.

I'm quite new to php. Can anyone tell me what I'm doing wrong?

(PS I know I have to add something to the if-statement like '$post[post_status] != trash' to make sure only the published posts are set to private, but I try to focus on selecting posts from the given category first)


Solution

  • You compare array of objects with array of ints. You should extract ID's of categories:

    function force_type_private($post) {        
      if (in_array(11, array_column(get_the_category($post->ID), 'term_id'))) { 
            $post['post_status'] = 'private';
      }
    
      return $post;
    }
    
    add_filter('wp_insert_post_data', 'force_type_private');