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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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);
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0