Php 在Woocommerce中从商店页面的类别列表中隐藏产品类别
我想在Woocommerce商店页面的类别列表中隐藏某个产品类别。我找到并使用了以下代码段:Php 在Woocommerce中从商店页面的类别列表中隐藏产品类别,php,wordpress,woocommerce,widget,custom-taxonomy,Php,Wordpress,Woocommerce,Widget,Custom Taxonomy,我想在Woocommerce商店页面的类别列表中隐藏某个产品类别。我找到并使用了以下代码段: 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_
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;
}
我的wp config中有一个debug选项设置为true,因此,当代码段工作且“books”类别从列表中隐藏时,我收到以下错误:
Notice:: Trying to get property of non-object in
它指向这条线:
if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_shop() )
这行写对了吗?还是我遗漏了什么?更新:您最好使用
unset()
从数组中删除产品类别术语,方法如下:
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;
}
此代码位于活动子主题(或主题)的function.php文件中
已测试并正常工作(不会引发错误)。已更新:您最好使用
unset()
从数组中删除产品类别术语,方法如下:
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;
}
此代码位于活动子主题(或主题)的function.php文件中
已测试并正常工作(不会抛出错误)。感谢您的帮助。。它只适用于小部件,但不适用于类别列表。基本上,在我的店铺页面上,我在店铺名称下方有一个类别列表。但它不是一个小部件。我的代码适用于这一个,不需要的类别从列表中消失,但它触发了如上所述的通知错误..如果我编辑archive-product.php模板呢?类别列表显示为
$terms=get_terms('product_cat')代码>我可以在这里排除该类别吗?@JoeBloggs我已经更新了我的代码…试试看。这一次应该不会有任何错误。谢谢,代码可以工作,但我还是遇到了一个棘手的问题注意:试图在
中获取非对象的属性,指向这一行if('books'=$term->slug&&$term->taxonomy='product_cat')
会是别的吗?与代码冲突?@JoeBloggs我没有得到那个错误…但是我已经稍微更新了代码,在$term
上使用PHP条件is_object()
,以确保它是一个对象(WP_term object实例)…所以试试吧…我希望它能工作。谢谢你的帮助。。它只适用于小部件,但不适用于类别列表。基本上,在我的店铺页面上,我在店铺名称下方有一个类别列表。但它不是一个小部件。我的代码适用于这一个,不需要的类别从列表中消失,但它触发了如上所述的通知错误..如果我编辑archive-product.php模板呢?类别列表显示为$terms=get_terms('product_cat')代码>我可以在这里排除该类别吗?@JoeBloggs我已经更新了我的代码…试试看。这一次应该不会有任何错误。谢谢,代码可以工作,但我还是遇到了一个棘手的问题注意:试图在
中获取非对象的属性,指向这一行if('books'=$term->slug&&$term->taxonomy='product_cat')
会是别的吗?与代码冲突?@JoeBloggs我没有得到那个错误…但是我已经轻轻地更新了代码,在$term
上使用PHP条件is\u object()
,以确保它是一个对象(一个WP\u term对象实例)…所以试试吧…我希望它能工作。