0

I would like to create a condition to manually hide product categories within the shop. I already started from a code base but I am trying to understand why if I put the is_product_category() condition the error comes out as I specified in the question with PHP Version 8.0

This is the code:

add_filter( 'get_terms', 'sct_hide_cat', 10, 3 );

function sct_hide_cat( $terms, $taxonomies, $args ) {

//global $product;
$exclude = [50, 22, 20, 31, 35, 45, 40, 65, 37, 40, 3434];
$new_terms = [];

if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_shop() || is_product_category() ) {
    foreach ( $terms as $key => $term ) {
        if ( ! in_array( $term->term_id, $exclude ) ) { 
            $new_terms[] = $term;
        }
    }
    $terms = $new_terms;
}
return $terms;
}
2
  • print $terms and see if everything is expected, likely it is not. Commented Aug 10, 2022 at 11:29
  • get_terms is a filter applied by get_terms() which doesn't always return an array, and even when it's an array, it's not always an array of objects. And in your case, the "term_id" on int in the error implied that the $terms was an array of term IDs instead of objects. So you can't simply use $term->term_id, because $term could be a term ID, name, etc. and is not necessarily an object.
    – Sally CJ
    Commented Aug 10, 2022 at 12:46

1 Answer 1

1

You can I think you should use get_terms_args filter instead of get_terms and just add exclude arg, so now get_terms() function won't retrieve those cats and you'll get right count. Here's code example:

add_filter( 'get_terms_args', 'mamaduka_edit_get_terms_args', 10, 2 );
/**
* Exclude product categories from Woocommerce
*
*/
function mamaduka_edit_get_terms_args( $args, $taxonomies ) {
 //print_r($taxonomies);
if ( is_admin() && 'product_cat' !== $taxonomies )
    return $args;

$args['exclude'] = [50, 22, 20, 31, 35, 45, 40, 65, 37, 40, 3434]; // Array of cat ids you want to exclude
return $args;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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