Skip to content
Advertisement

Woocommerce Product Category taxonomy in Admin Pages

I’m writing a plugin for WordPress using WooCommerce. I need to get the list of WooCommerce Product Categories (taxonomy 'product_cat') in the admin page of the plugin (note the emphasis on “admin page”). However following calls to get_categories() and to get_terms() filtering by taxonomy result in error (I’ve simplified the code. Submenu class is somewhere else and as I understand it doesn’t interfere):

add_action( 'init', 'myplugin_admin_settings' );
function myplugin_admin_settings() {
    $plugin = new Submenu( new MyPlugin_Admin_Page('myplugin_options') );
    $plugin->init();
}
class MyPlugin_Admin_Page {
    public function __construct($option_name) {
        $args = array(
            'taxonomy'     => 'product_cat',
            'hide_empty'   => false
        );
        var_export(get_categories( $args ));  // Prints 'error'
        var_export(get_terms( $args ));       // Prints 'error'
        var_export(get_terms());              // Prints the whole list of terms including those belonging to 'product_cat' taxonomy
    }
}

The error printed is:

WP_Error::__set_state(array(   'errors' =>   array (    'invalid_taxonomy' =>     array (      0 => 'Invalid taxonomy.',    ),  ),   'error_data' =>   array (  ),))array (  '' => NULL,)

Which indicates that taxonomy doesn’t exist. And indeed if I call to taxonomy_exists('product_cat') it says false. However the whole list of terms printed include those belonging to 'product_cat', which seems impossible if the taxonomy doesn’t exist. That kills me. As an example:

  43 =>
  WP_Term::__set_state(array(
 'term_id' => 56,
 'name' => 'Accesorios',
 'slug' => 'accesorios',
 'term_group' => 0,
 'term_taxonomy_id' => 56,
 'taxonomy' => 'product_cat',
 'description' => '',
 'parent' => 0,
 'count' => 1,
 'filter' => 'raw',
  )),

These calls are done in init hook, so they should return the Product Categories.

Anyone can understand what’s happening? Is there other way to get the Product Categories in Admin Pages?

Thanks.

EDIT: I’ve tried also with hooks plugins_loaded and woocommerce_init.

Advertisement

Answer

Well, I don’t know what really happened, but now it’s working using init hook. I tried before, but it didn’t, not sure why. Now I just did 2 tests: use function current_filter() to check that the function itself was properly hooked; and hook to init a function containing the call to get_terms($args). Then I noticed it was working and I undo the changes and everything was working. Ghost fail.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement