I am trying to call wp_set_object_terms in a function hooked to custom post creation (via wp_insert_post_data) to set taxonomies tags for the post from a custom field:
$item_brand = ( ! empty( $_POST[ 'brand' ] ) ) ? $_POST[ 'brand' ] : get_post_meta( $postarr[ 'ID' ], 'brand', true ); wp_set_object_terms( $postarr[ 'ID' ], $item_brand, 'brand', false);
The function has no issues creating the taxonomy terms from the custom field when the post is created or modified, but it does not set the terms for the post. My guess is that it is an issue processing the post ID variable, as I tried to set a static post ID in the wp_set_object_terms call and the post with the static ID was assigned the new tags. So I tried this to mitigate any issues with parsing the current ID:
$post_id = intval ((! empty( $_POST[ 'ID' ] ) ) ? $_POST[ 'ID' ] : $postarr[ 'ID' ]); wp_set_object_terms( $post_id, $item_brand, 'brand', false);
but it did not help, I also know that I am successfully getting the post ID with the above as I am using it for other purposes within the function, its just not working for wp_set_object_terms. Honestly not sure where to look further at this point and would appreciate any suggestions that might 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
wp_insert_post_data is applied before the post data are inserted to the database. use the save_post hook instead to set the custom taxonomy terms.
That was it. Thanks Sally for the recommendation.
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