Joe*_*ggs 1 php wordpress widget custom-taxonomy woocommerce
我想在 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_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;
}
Run Code Online (Sandbox Code Playgroud)
我的 wp-config 中有一个调试选项设置为 true ,因此当代码段正在运行并且“书籍”类别从列表中隐藏时,我收到以下错误:
Notice:: Trying to get property of non-object in
Run Code Online (Sandbox Code Playgroud)
它指向这一行:
if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_shop() )
Run Code Online (Sandbox Code Playgroud)
这行写对了吗?或者我错过了什么?
更新:您最好使用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;
}
Run Code Online (Sandbox Code Playgroud)
此代码位于活动子主题(或主题)的 function.php 文件中。
已测试并有效(不会引发错误)。
| 归档时间: |
|
| 查看次数: |
2505 次 |
| 最近记录: |