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);
Actually, you can use multiple actions, at least this is what at the end of the wp_delete_term function, which runs when you click Delete on a taxonomy term:
The last one my be the most useful, you can create an add action like this:
The hook that is running before deleting the term is
'delete_term_taxonomy'
And it is the hook needed in order to use the term_id before it gets deleted.Now, we can proceed to retrieve the
term
object and delete thepostmeta
related to the term being deleted.The code is as follows:
As @passatgt stated there are at least 4 actions to hook.
Btw the most useful is “delete_$taxonomy” action.
The action accepts 3 parameters. To use all of them you have to explicit declare how many parameters you want to receive in the callback function. You can do this by specifing it as 3rd parameter of
add_action($hook, $function_to_add, $priority, **$accepted_args** );
.