Using get_term() in functions.php results in Invalid taxonomy error

I don’t know why get_term() works on other pages but won’t work in functions.php. Using get_term() in functions.php causes WordPress to report the error Invalid taxonomy.

my function.php which is ajax handler and already registered for ajax

 public function load_destination()
    {
        global $wpdb;
        $termId = $_POST['termid']; 
       $term =  get_term($termid,'package_state');
       $args = array(
'post_type' => 'package',
'tax_query' => array(
    array(
    'taxonomy' => 'package_state',
    'field' => 'id',
    'terms' => $termId
     )
  )
);

$query = new WP_Query( $args );
$collection=[];
$count =1;
while($query->have_posts()) : $query->the_post();

$collection['data'][] = // i need to set term data here $term;


$count++;
endwhile;
    wp_send_json($collection);    
    }

2 Answers
2

It sounds like you are are using get_term() for a custom taxonomy. If you’re using get_term() inside functions.php and outside of a hooked function, that code is going to be run immediately when functions.php is loaded. Your custom taxonomy will not have been registered at this point, because that happens on the init hook.

Your code is working inside of your page template because WordPress has loaded the custom taxonomies at that point.

If you were to try something like $term = get_term( '2', 'category' ); (where 2 is a valid term ID) in functions.php, it would actually work, because WordPress loads built-in taxonomies in wp-settings.php (which is very early in the loading process) for backwards compatibility reasons. WordPress also registers default taxonomies on init, by the way. This is explained in the documentation block for create_initial_taxonomies() in /wp-includes/taxonomy.php.

Anyway, running get_term() outside of a hooked function in functions.php is not the right way to do it, and more code would be needed to help you further.

Leave a Comment