Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top