Oko*_*uko 5 php wordpress categories user-roles woocommerce
我有一个客户端有以下问题:
我需要能够将他们的WooCommerce WordPress网站分为两类.如果用户以a身份登录"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.
}
}
Run Code Online (Sandbox Code Playgroud)
我浏览了StackOverflow,但是我还没找到我正在寻找的内容,或者非常清楚我应该使用哪些关键字进行搜索.
你能为我指出正确的方向吗?
对的,这是可能的.有两种方式:
1)使用在pre_get_posts创建查询变量对象之后但在运行实际查询之前调用的wordpress钩子.所以它非常适合这种情况.我们在这里想象类别的ID 'Wholesale'是'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' );
Run Code Online (Sandbox Code Playgroud)
此代码位于活动子主题或主题的function.php文件中,或者更好地在自定义插件中.
2)使用woocommerce_product_queryWooCommerce钩子.(我们在这里仍然想象'Wholesale'类别的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' );
Run Code Online (Sandbox Code Playgroud)
此代码位于活动子主题或主题的function.php文件中,或者更好地在自定义插件中.
如果要使用类别slug而不是类别ID,则必须部分替换(两个数组):
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'wholesale', // your category slug (to use the slug see below)
Run Code Online (Sandbox Code Playgroud)
你可以添加,如果你愿意和需要,一些woocommerce条件标签,以if statements进一步限制这一点.
参考文献: