1

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

1 Answer 1

1

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);
}
1
  • Thanks a lot for your reply .. Yep you are right.. but isn't it Object instead of array.. I am using $post->ID works now.. thanks for the alternate method too - publish_post Jul 14, 2021 at 10:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.