Reputation: 1462
I wanted to hide a certain product category in the category list on the Woocommerce shop page. I found and used the following snippet to do so:
add_filter( 'get_terms', 'exclude_category', 10, 3 );
function exclude_category( $terms, $taxonomies, $args ) {
$new_terms = array();
// if a product category and on a page
if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_shop() )
{
foreach ( $terms as $key => $term ) {
if ( ! in_array( $term->slug, array( 'books' ) ) ) {
$new_terms[] = $term;
}
}
$terms = $new_terms;
}
return $terms;
}
I have a debug option in my wp-config set to true and so while the snippet is working and the 'books' category is hidden from the list, I am getting the following error:
Notice:: Trying to get property of non-object in
And it is pointing to this line:
if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_shop() )
Is this line written correctly? or am I missing something?
Upvotes: 3
Views: 3719
Reputation: 253773
Updated: You should better use unset()
to remove the product category term from the array, this way:
add_filter( 'get_terms', 'exclude_category', 10, 3 );
function exclude_category( $terms, $taxonomies, $args ) {
$new_terms = array();
if ( is_shop() ){
foreach ( $terms as $key => $term ) {
if( is_object ( $term ) ) {
if ( 'books' == $term->slug && $term->taxonomy = 'product_cat' ) {
unset($terms[$key]);
}
}
}
}
return $terms;
}
This code goes on function.php file of your active child theme (or theme).
Tested and works (does't throws an error).
Upvotes: 11