如果訪問者未登錄或用戶角色為“客戶” ,我試圖限制產品出現在檔案/搜索結果中
我正在使用這個片段:
// Check User Role
function banks_has_user_role($check_role){
$user = wp_get_current_user();
if(in_array( $check_role, (array) $user->roles )){
return true;
}
return false;
}
// // Hide products in specific category from not logged-in users and user role customer
add_filter( 'woocommerce_product_query_tax_query', 'exclude_products_fom_unlogged_users', 10, 2 );
function exclude_products_fom_unlogged_users( $tax_query, $query ) {
global $user, $product;
if( ! is_user_logged_in() ){
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN', // or 'NOT IN' to exclude feature products
);
}
else if(banks_has_user_role('customer')){
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN', // or 'NOT IN' to exclude feature products
);
}
return $tax_query;
}
// The query
$query = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $products,
'orderby' => $orderby,
'order' => $order == 'asc' ? 'asc' : 'desc',
'tax_query' => $tax_query // <===
) );
測驗時,我確定我的未登錄狀態可以作為特色產品不再顯示,但我現在似乎可以無限加載。有什么建議嗎?
uj5u.com熱心網友回復:
看來您正在使用不必要的步驟。您的代碼嘗試的這個縮短和修改版本應該足以為未登錄的客戶或具有用戶角色的用戶隱藏特色產品'customer'
所以你得到:
function filter_woocommerce_product_query_tax_query( $tax_query, $query ) {
// NOT for backend
if ( is_admin() ) return $tax_query;
// Guest user OR user role = customer
if ( ! is_user_logged_in() || current_user_can( 'customer' ) ) {
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'NOT IN',
);
}
return $tax_query;
}
add_filter( 'woocommerce_product_query_tax_query', 'filter_woocommerce_product_query_tax_query', 10, 2 );
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/476997.html
標籤:php WordPress woocommerce 产品 用户角色
上一篇:LaravelhasOne不能只來自關系模型的一個屬性
下一篇:如何對Laravel集合進行分頁