get_term and get_term_by return null or false, even though term exists

I am trying to use the action hooks delete_term and delete_$taxonomy, among other hooks that delete a term, but they are presenting the same issue.

For example, 1234 is an existing term in the favorite custom taxonomy:

Read More
add_action( 'delete_favorite', function( $term, $tt_id ) {

    $get_term1 = get_term( $term, 'favorite' );
    $get_term2 = get_term( 1234, 'favorite' );

    $get_term_by1 = get_term_by( 'id', $term, 'favorite' );
    $get_term_by2 = get_term_by( 'id', 1234, 'favorite' );
    $get_term_by3 = get_term_by( 'name', 'term-name', 'favorite' );

    $output = 'get_term1: ' . $get_term1 . ' get_term2: ' . $get_term2 . 
        ' get_term_by1: ' . $get_term_by1 . ' get_term_by2: ' . $get_term_by2 . 
        ' get_term_by3: ' . $get_term_by3;

    ob_start();
    var_dump( $output );
    $contents = ob_get_contents();
    ob_end_clean();
    error_log( $contents );

}, 10, 2 );

They all return nothing. So, how can I get the term inside these types of functions?

The functions get_term and get_term_by work everywhere else but inside these hooks. What is wrong?

Related posts

Leave a Reply

1 comment

  1. To use get_term_by we need the term object before it gets deleted. Therefore, we should use the action hook delete_term_taxonomy that runs before the term is deleted.

    Now, we can go ahead and perform some tasks such as deleting all the postmeta related to the term being deleted.

    The code is:

    add_action( 'delete_term_taxonomy', function($tt_id) {
    
        $taxonomy = 'category';    
        $term = get_term_by('term_taxonomy_id', $tt_id, $taxonomy); 
        $user_name = $term->name;
        $meta_key = "_category_relation_added_" . $user_name;
        delete_post_meta_by_key( $meta_key );
    
    }, 9, 1);