Warning: Attempt to read property "term_id" on int - Woocommerce

Viewed 46

I would like to create a condition to manually hide 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;
}
1 Answers

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;
}
Related