Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get_terms gives "invalid taxonomy" from plugin

I'm building a plugin for woocommerce and i have some troubles. I'm trying to get all avalible product categories.

the code simply looks like this:

$cats = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC',  'parent' =>0));
print_r($cats);

This gives me

WP_Error Object
(
    [errors:WP_Error:private] => Array
        (
            [invalid_taxonomy] => Array
                (
                    [0] => Invalid taxonomy
                )
        )
    [error_data:WP_Error:private] => Array
    (
    )
)

Do i need to hook this to some special init or something? I tried the same code in functions.php but with the same error.

EDIT: Yep, i found a soluiton to the problem. I added

add_action('init', 'runMyPlugin');

did the trick!

like image 872
gubbfett Avatar asked Oct 25 '14 15:10

gubbfett


2 Answers

Just adding a full code example

add_action('init', 'my_get_woo_cats');

function my_get_woo_cats() {
    $cats = get_terms( array( 'taxonomy' => 'product_cat','hide_empty' => 0, 'orderby' => 'ASC',  'parent' =>0) );
    print_r($cats);
}
like image 55
stillatmylinux Avatar answered Oct 21 '22 05:10

stillatmylinux


I had the same problem. For Woocomerce you can be resolved by adding the below code in functions.php:

register_taxonomy( 'product_cat', array('product'), array() );
like image 37
hossein naghneh Avatar answered Oct 21 '22 05:10

hossein naghneh