I need to delete some postmeta
when deleting taxonomy terms from the backend. Before deleting the term
, I need to retrieve the postmeta's meka_key
and the term id
that is going to be deleted. Use the term id
to perform some tasks and then delete the postmeta
and term
.
I already tried using the action hook set_object_terms
however, I cannot retrieve the term id
when deleting the term
because it returns an empty array. So, I would need to somehow get the term id
before it gets deleted.
How can I retrieve the term id before deleting it?
add_action( 'set_object_terms', function( $object_id, $terms, $tt_ids, $taxonomy ){
//$terms is returning the term's name (when adding an object id),
//it's returning empty when deleting the term.
//I need to have a valid $terms when deleting it, where can I get it?
$user_name = $terms;
$meta_key = '_favorite_relation_added_' . $user_name;
// Customize post type in next line according to your needs. I used 'category' as example
if ( $taxonomy === 'favorite' ) {
$post = get_post( $object_id );
if ( empty( $post ) ) return;
// Customize post type in next line according to your needs. I used 'post' as example
if ( $post->post_type !== 'post' ) return;
// let's see if the post has some terms of this category,
// because the hoook is fired also when terms are removed
$has_terms = get_the_terms( $object_id, $taxonomy );
// here we see if the post already has the custom field
$has = get_post_meta( $post->ID, $meta_key, true );
if ( ! $has && ! empty( $has_terms ) ) {
// if the post has not the custom field but has some terms,
// let's add the custom field setting it to current timestamp
update_post_meta( $post->ID, $meta_key, time() );
} elseif ( $has && empty( $has_terms ) ) {
// on the countrary if the post already has the custom field but has not terms
// (it means terms are all removed from post) remove the custom fields
delete_post_meta( $post->ID, $meta_key );
}
}
}, 10, 4);