Set post terms on post publish

I am trying to set post terms on the post, when it is puublished

I use following code but is doesn't work

add_action('pending_to_publish', 'oj_publish_post');
function oj_publish_post($post_id) {
  $taxonomy = 'category';
  $term_id = array(8);
  $term_id = array_map('intval', $term_id);    
  wp_set_post_terms( $post_id ,$term_id, $taxonomy,true);
}

But, when I pass the id of the post manually i.e instead of using post_id. I use 773 it works

   add_action('pending_to_publish', 'oj_publish_post');
    function oj_publish_post($post_id) {
      $taxonomy = 'category';
      $term_id = array(8);
      $term_id = array_map('intval', $term_id);    
      wp_set_post_terms( 773 ,$term_id, $taxonomy,true);
    }

What am I doing wrong, please help

Topic terms taxonomy publish Wordpress

Category Web


The argument from pending_to_publish action, $post_id in your case, is not ID but array (callback to publish).

I think it would be better to use the publish_post action, that way $post_id will actualy be the post id.

Also this is a very general action so if you have multiple post types it would be wise to check if the current post type is the actual one you want to add the term to

Edited answer

Or in your case you can pass the post id as following

add_action('pending_to_publish', 'oj_publish_post');
function oj_publish_post($post) {
  $taxonomy = 'category';
  $term_id = array(8);
  $term_id = array_map('intval', $term_id);    
  wp_set_post_terms( $post->ID ,$term_id, $taxonomy,true);
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.