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

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);