我需要能够将他们的WooCommerce WordPress网站分为两类.如果用户以“Wholeseller”身份登录,则只会从数据库中提取“Wholesale”类别中的产品.
但是,如果用户未登录或登录但不是“Wholeseller”,则只有没有“Wholesale”类别的产品才会从数据库中删除.
我想我会在主题的functions.PHP文件中添加这样的东西:
add_filter("some_woocommerce_hook", "wholeseller_filter");
function wholeseller_filter() {
if (current_user->role == "Wholeseller"){
//omit products without "wholesale" category while browsing whole site
} else {
//omit products with "wholesale" in the category while browsing whole site.
}
}
我浏览过StackOverflow,但是我还没找到我正在寻找的内容,或者非常清楚我应该使用哪些关键字进行搜索.
你能为我指出正确的方向吗?
解决方法:
对的,这是可能的.有两种方式:
1)使用在创建查询变量对象之后但在运行实际查询之前调用的pre_get_posts wordpress钩子.所以它非常适合这种情况.我们在这里想象’批发’类别的ID是’123′.
function wholeseller_role_cat( $query ) {
// Get the current user
$current_user = wp_get_current_user();
if ( $query->is_main_query() ) {
// displaying only "Wholesale" category products to "whole seller" user role
if ( in_array( 'wholeseller', $current_user->roles ) ) {
// Set here the ID for Wholesale category
$query->set( 'cat', '123' );
// displaying All products (except "Wholesale" category products)
// to all other users roles (except "wholeseller" user role)
// and to non logged user.
} else {
// Set here the ID for Wholesale category (with minus sign before)
$query->set( 'cat', '-123' ); // negative number
}
}
}
add_action( 'pre_get_posts', 'wholeseller_role_cat' );
此代码位于活动子主题或主题的function.PHP文件中,或者更好地在自定义插件中.
2)使用woocommerce_product_query WooCommerce钩子. (我们仍然在这里想象’批发’类别的ID是’123′.
function wholeseller_role_cat( $q ) {
// Get the current user
$current_user = wp_get_current_user();
// displaying only "Wholesale" category products to "whole seller" user role
if ( in_array( 'wholeseller', $current_user->roles ) ) {
// Set here the ID for Wholesale category
$q->set( 'tax_query', array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => '123', // your category ID
)
) );
// displaying All products (except "Wholesale" category products)
// to all other users roles (except "wholeseller" user role)
// and to non logged user.
} else {
// Set here the ID for Wholesale category
$q->set( 'tax_query', array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => '123', // your category ID
'operator' => 'NOT IN'
)
) );
}
}
add_action( 'woocommerce_product_query', 'wholeseller_role_cat' );
此代码位于活动子主题或主题的function.PHP文件中,或者更好地在自定义插件中.
如果要使用类别slug而不是类别ID,则必须部分替换(两个数组):
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'wholesale', // your category slug (to use the slug see below)
您可以根据需要添加,在if语句中使用some woocommerce conditionals tags来限制更多.
参考文献:
> Modifying the WooCommerce Product Query
> I can’t fetch WooCommerce products by category id
> WordPress Class Reference – WP Query