Your problem is that your trying to access taxonomy data before it is registered.
This doesn’t work:
add_action('init', 'json_handler');
function json_handler(){
$categories = get_terms( 'my_cat', 'orderby=count&hide_empty=0' );
if( ! is_wp_error( $categories ) ) {
// encode the $categories array as json
print_r( json_encode( $categories ) );
}
}
add_action('init', 'create_stores_nonhierarchical_taxonomy');
function create_stores_nonhierarchical_taxonomy() {
// Labels part for the GUI
$labels = array(
'name' => _x( 'Store Categories', $this -> textdomain ),
//Rest of your labels
);
// Now register the non-hierarchical taxonomy like tag
register_taxonomy('my_cat',$this->post_type,array(
'labels' => $labels,
'hierarchical' => true,
'show_ui' => true,
'how_in_nav_menus' => true,
'public' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'my_cat' ),
));
}
This works:
add_action('init', 'create_stores_nonhierarchical_taxonomy');
function create_stores_nonhierarchical_taxonomy() {
// Labels part for the GUI
$labels = array(
'name' => _x( 'Store Categories', $this -> textdomain ),
//Rest of your labels
);
// Now register the non-hierarchical taxonomy like tag
register_taxonomy('my_cat',$this->post_type,array(
'labels' => $labels,
'hierarchical' => true,
'show_ui' => true,
'how_in_nav_menus' => true,
'public' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'my_cat' ),
));
}
add_action('init', 'json_handler');
function json_handler(){
$categories = get_terms( 'my_cat', 'orderby=count&hide_empty=0' );
if( ! is_wp_error( $categories ) ) {
// encode the $categories array as json
print_r( json_encode( $categories ) );
}
}
Change the order, as I did above, is not a good solution for maintainability. A better solution would be:
1.- Register the taxonomy on init
with low priority (default priority is 10, actions with same priority are executed in the order they appear):
add_action( 'init', array($this, 'create_stores_nonhierarchical_taxonomy'), 1 );
2.- Try to access taxonomy data after init
event, so you are sure the taxonomy has been registered, or on init
events with priority higher than priority of taxonomy register callback, in this example with priority higher than 1.
Note: registering a taxonomy before or after init
is not recommended.