我正在尝试从 Shop
和 product archive
页面的类别列表小部件中为 其他用户排除
。但由于某种原因,它不起作用。一个类别
比管理员
任何帮助,谢谢。
function exclude_category( $terms, $taxonomies, $args ) {
$new_terms = array();
/*if ( !is_admin() && ( is_product() || is_shop() || is_product_category() || is_product_tag() ) ){ */
if ( !is_admin() || is_product() || is_shop() || is_product_category() || is_product_tag() ){
foreach ( $terms as $key => $term ) {
if( is_object ( $term ) ) {
if ( 'some-category' == $term->slug && $term->taxonomy = 'product_cat' ) {
unset($terms[$key]);
}
}
}
}
return $terms;
}
add_filter( 'get_terms', 'exclude_category', 10, 3 );
最佳答案
在 WooCommerce 上排除产品类别
改为使用以下条件检查:
- 要检查用户是否是管理员,您可以使用从
wp_get_current_user
Docs 返回的用户对象的roles
属性功能。 - 要检查您是否在 woocommerce 页面上(即
is_product() || is_shop() || is_product_category() || is_product_tag()
),您可以简单地使用此is_woocommerce()
函数。
所以整个代码是:
add_filter('get_terms', 'exclude_category', 10, 3);
function exclude_category($terms, $taxonomies, $args)
{
$roles = wp_get_current_user()->roles;
if
(
!in_array('administrator', $roles)
&&
is_woocommerce()
)
{
foreach ($terms as $key => $term)
{
if (is_object($term))
{
if ('decor' == $term->slug && $term->taxonomy == 'product_cat')
{
unset($terms[$key]);
}
}
}
}
return $terms;
}
注意:
- 我使用
'decor'
作为类别 slug 来测试我网站上的这个片段,所以不要忘记用你自己的类别 slug 替换它。
结果如下:
排除 Wordpress 上的类别
add_filter('get_terms', 'exclude_category', 10, 3);
function exclude_category($terms, $taxonomies, $args)
{
$roles = wp_get_current_user()->roles;
if (
!in_array('administrator', $roles)
)
{
foreach ($terms as $key => $term)
{
if (is_object($term))
{
if ('uncategorized' == $term->slug && $term->taxonomy == 'category')
{
unset($terms[$key]);
}
}
}
}
return $terms;
}
注意:
- 我使用
'uncategorized'
作为类别别名在我的网站上测试此代码段,所以不要忘记将其替换为您自己的类别别名。
在 WooCommerce 中排除多个类别
您可以设置一个数组并使用in_array
函数进行条件检查。像这样:
$excluded_cat_slugs = array ('hoodies', 'decor');
if(in_array($term->slug, $excluded_cat_slugs) && $term->taxonomy == 'product_cat')
在 Wordpress 中排除多个类别
$excluded_cat_slugs = array ('uncategorized', 'test-category');
if(in_array($term->slug, $excluded_cat_slugs) && $term->taxonomy == 'category')
关于php - 如何从非管理员用户的类别列表小部件中排除类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70952494/