-1

I am tried to display all product category with bellow function .. getting a error Invalid taxonomy .. it's was working fine last 2 installation..

    function be_woocommerce_category_id(){
        $categories_array = array();
        $categories_array[0] = esc_html__('Choose a Category', 'shopstore'); 
        $args = array(
                    'orderby'    => 'title',
                    'order'      => 'ASC',
                );
        $categories = get_terms( 'product_cat', $args );

        if( count($categories) > 0 ){
            foreach( $categories as $category ){
              $categories_array[$category->term_id] = $category->name; 
            }
        }
        return $categories_array; 
}
  • Where and when are you running this function? – Jacob Peattie Feb 14 at 9:37
  • it's default woocomerce hook – Saiful Islam Feb 14 at 9:41
  • Which hook? Specifically. – Jacob Peattie Feb 14 at 9:48
1

it's was working fine last 2 installation

Those two installation might still be on WordPress prior to version 4.5.0, and according to the reference:

Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the $args array

So:

$args = array(
  'orderby'  => 'title',
  'order'    => 'ASC',
  'taxonomy' => 'product_cat',
);
$categories = get_terms( $args );

If that doesn't work, then maybe on the new installation, your code is executed before the product_cat taxonomy is registered.

  • it's showing object(WP_Error)#808 (2) { ["errors"]=> array(1) { ["invalid_taxonomy"]=> array(1) { [0]=> string(17) "Invalid taxonomy." } } ["error_data"]=> array(0) { } } – Saiful Islam Feb 14 at 9:39
  • WooCommerce registers its custom taxonomies during the init hook with 5 being the priority. So if your code is called from a hook (action/filter), then make sure the hook is fired after init or that the priority is at least 6. And FYI, the taxonomies are not yet registered in either the woocommerce_loaded or woocommerce_init hook/action. – Sally CJ Feb 14 at 11:02
0

I had the same 'problem' a few days ago. Like Sally CJ edited, this may be a registration issue.
When I called term_exists(), the expected term_id was returned, but get_term() returned the Invalid taxonomy error.
My solution was to call the register_taxonomy function in my function and everything was fine.
Edit:
I called it like that (with an empty array as $args):

register_taxonomy( 'taxonomy_name', array('the_custom_post_type'), array() );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.