wp_set_object_terms won’t work inside wp_insert_post hook in front end form (non admin page)
I have been trying this for days without any successs. I created a function in my child theme function.php. What I am trying to do is whenever a post gets saved or inserted, I want to update it’s category. The post and category are customs.
The code below is shortened and hardcoded for the purpose of the question.
add_action('wp_insert_post', 'custom_function_sync_category', 20);
function custom_function_sync_category($post_id){
$term_taxonomy_ids = wp_set_object_terms( 2446, 219, 'advert-category', true);
log($term_taxonomy_ids); //returns success
/* Log Output:
Array
(
[0] => 219
)
*/
//2446 is the postid
//219 the category should be assigned
}
So whenever I update/insert post in the admin area it works 100%.
When I update/insert post in the front end form (non-admin page), the functions gets triggered and it logs success but the category doesn’t get assigned.
If I hook this function to add_action('init', 'custom_function_sync_category', 20);
It will work 100% on page refresh.
I don’t know what I am missing. Read many topics says move your function to init
and yes it works but how will I be able to run this function on save_post
/ wp_insert_post
to edit the saved/inserted post.
I tried using wp_set_post_terms
but it doesn’t work also. Played with the priority from default to 999.
This is frustrating, keep thinking about this all day.
Appreciate any help,
Thank you in advance,
Leave an answer
You must login or register to add a new answer .