0

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.

1
  • Note that the filter wp_insert_post_data is applied before the post data are inserted to the database, so the post ID is empty (or 0) if the post is being created and not updated. Hence, you should use the save_post hook instead to set the custom taxonomy terms. Or try with that and see if it works? – Sally CJ May 5 at 1:36
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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