2 回答

TA貢獻1777條經驗 獲得超10個贊
當用戶不被允許時,以下代碼將根據您的自定義產品字段過濾產品(如果他們嘗試手動訪問受保護的產品,則會將他們重定向到商店頁面)。
// Conditional function checking for authorized users
function is_authorized_user(){
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$caps = $user->allcaps;
if ( ( isset($caps['edit_product']) && $caps['edit_product'] )
|| in_array( 'verified_buyer', $user->roles ) ) return true;
}
else return false;
}
// Filter product query (and search) from unauthorized users
add_filter( 'woocommerce_product_query_meta_query', 'only_authorized_users_meta_query', 10, 2 );
function only_authorized_users_meta_query( $meta_query, $query ) {
// Hide specific products from unauthorized users
if( ! is_authorized_user() && ! is_admin() ) {
$meta_query['relation'] = 'OR';
$meta_query[] = array(
'key' => '_hide_from_unauthorize_users',
'value' => 'no',
'compare' => '='
);
$meta_query[] = array(
'key' => '_hide_from_unauthorize_users',
'compare' => 'NOT EXISTS'
);
}
return $meta_query;
}
// Security: Redirect unauthorized users if accessing prodtected products
add_action( 'template_redirect', 'only_authorized_users_redirect' );
function only_authorized_users_redirect() {
// Specific products redirect for unauthorized users (to be sure)
if( is_product() && ! is_authorized_user()
&& get_post_meta( get_the_id(), '_hide_from_unauthorize_users', true ) === 'yes' ) {
wp_safe_redirect( get_permalink( wc_get_page_id( 'shop' ) ) );
exit;
}
}
代碼位于活動子主題(或活動主題)的 functions.php 文件中。測試和工作。
您可以不使用其他用戶角色,而是:
1)使用WC_Customer is_paying_customer布爾屬性,如:
if( WC()->customer->get_is_paying_customer() ) {
// Is a playing customer
} else {
// NOT a playing customer
}
2)或添加自定義用戶元為:
update_user_meta( get_current_user_id(), 'allowed_customer', '1' );
然后您將使用以下方法進行檢查:
if( get_user_meta( get_current_user_id(), 'allowed_customer', true ) ) {
// Allowed customer
} else {
// NOT Allowed customer
}

TA貢獻1829條經驗 獲得超7個贊
當您說“刪除”時,我假設您實際上是在嘗試隱藏該產品。
所以,使用pre_get_posts動作鉤子是你的方法。
下面的代碼會隱藏有其領域的任何產品_hide_from_unauthorize_users設置為yes從沒有被登錄的用戶中,并從已登錄的用戶,但不是一個verified_buyer,也不是administrator。
將下面的代碼片段放在您的functions.php文件中并注意注釋:
<?php
/**
* @param WP_Query $query
*/
function _hide_products_from_certain_users( $query ) {
if ( is_admin() ) {
return;
}
/**
* Create the query which will make sure only products that are allowed to bee seen will show up.
*/
$meta_query[] = array(
'key' => '_hide_from_unauthorize_users',
'value' => 'yes',
'compare' => '!=',
);
$user = wp_get_current_user();
// If user is not logged in.
if ( ! is_user_logged_in() ) {
$query->set( 'meta_query', $meta_query );
} else {
$authorized_user_role = in_array( 'verified_buyer', (array) $user->roles );
$admin_role = in_array( 'administrator', (array) $user->roles );
// If the current user is not a verified_buyer nor an administrator.
if ( ! $authorized_user_role && ! $admin_role ) {
$query->set( 'meta_query', $meta_query );
}
}
}
add_action( 'pre_get_posts', '_hide_products_from_certain_users' );
順便說一句,你的代碼中有一些語法錯誤,我修復了它們。
- 2 回答
- 0 關注
- 203 瀏覽
添加回答
舉報