Ajax and WP_Query/tax_query parameter

Your code looks fine, but it’s failing because your custom taxonomy is not getting registered anywhere in the action hooks of an AJAX call.

My guess is that you are registering your custom taxonomies per the Taxonomies documentation, which tells you to add it to the “init” action hook. However, “init” doesn’t get called during an AJAX call. It only gets called during a typical page request or an admin page request (see the Action Reference documentation). (Note: action reference documentation in the codex seems really out of date, it doesn’t include any list of actions run during an AJAX request.)

Workaround: where you need access to your custom taxonomies, manually run the init action at the beginning of your ajax function like so:

function get_game_difficulty() {
  do_action("init");

  // Code that relies on custom taxonomies being registered can be used below.
  ...
}
add_action('wp_ajax_nopriv_get_game_difficulty', 'get_game_difficulty' );
add_action('wp_ajax_get_game_difficulty', 'get_game_difficulty' );

Leave a Comment