【问题标题】:Completely hide products from unauthorized users in WooCommerce在 WooCommerce 中对未经授权的用户完全隐藏产品
【发布时间】:2019-10-12 08:45:08
【问题描述】:

如果用户不是特定角色(例如经过验证的买家),我正在尝试从未登录的用户中完全删除一个/多个产品。

我已经能够使用以下代码创建一个名为 Verified Buyer 的新角色;

add_role(
    'verified_buyer',
    __( 'Verified Buyer', 'text-domain' ),
    array(
       'read'         => true,  
        'edit_posts'   => false,
    )
);
//This Role is same role capability as the WooCommerce Customer role

我还使用下面的代码向 WooCommerce 添加新产品页面添加了一个复选框

function hide_product_from_unathorised_users() {
  $args = array(
    'id' => '_hide_from_unauthorize_users',
    'label' => 'Hide Product from unauthorized users',
    'desc_tip' => true,
    'description' => __('Check this to hide this product from unauthorized users', 'text-domain')
  );
  woocommerce_wp_checkbox( $args );
}

add_action( 'woocommerce_product_options_advanced', 'hide_product_from_unathorised_users' );

// Save Fields
function product_custom_fields_save($post_id){
    // Custom Product Text Field
    $hide_product_unathorised_users = isset( $_POST['_hide_from_unauthorize_users'] ) ? 'yes' : 'no';
        update_post_meta($post_id, '_hide_from_unauthorize_users', esc_attr( $hide_product_unathorised_users ));
}
add_action('woocommerce_process_product_meta', 'product_custom_fields_save');

现在我有了这两个选项(用户角色和一个复选框以知道要隐藏哪个产品)...如果满足以下条件,我想隐藏此类产品;

完全隐藏产品(即使从搜索查询中)如果;
1. 产品上的复选框被选中&用户未登录
2. 选中产品和用户登录且未验证买家或管理员角色的复选框

这样

function hide_product_completely_conditionally() {

global $post;

$hide_product_checkbox = get_post_meta( $post->ID, '_hide_from_unauthorize_users', true )

$user = wp_get_current_user();
$authorized_user_role = in_array( 'verified_buyer', (array) $user->roles );
$admin_role = in_array( 'administrator', (array) $user->roles );

    if ( ($hide_product_checkbox == 'yes' && !is_user_loggedin()) || ($hide_product_checkbox == 'yes' && is_user_loggedin() && (!$authorized_user_role || !$admin_role) ) ) {

     //(...) HIDE SUCH PRODUCT COMPLETELY CODE THAT I'M NOT SURE HOW TO WRITE

    }
}

提前感谢您的帮助。

【问题讨论】:

    标签: php wordpress woocommerce product user-roles


    【解决方案1】:

    以下代码将在不允许用户访问时根据您的自定义产品字段过滤产品(如果他们尝试手动访问受保护的产品,则会将他们重定向到商店页面)

    // 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
     }
    

    【讨论】:

    • 非常感谢,我喜欢您添加的安全重定向...甚至没有想到,但有了它,它的效果比我想象的还要好。谢谢洛伊克
    【解决方案2】:

    当您说“删除”时,我假设您实际上是在尝试隐藏产品。

    因此,使用pre_get_posts 动作挂钩是您的最佳选择。

    下面的代码将隐藏其字段 _hide_from_unauthorize_users 设置为 yes 的任何产品,未登录的用户用户已登录但不是verified_buyer 也不是administrator

    把下面的sn-p放到你的functions.php文件中,注意cmets:

    <?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' );
    

    顺便说一句,您的代码中有一些语法错误,我已修复它们。

    【讨论】:

      猜你喜欢
      • 2015-10-29
      • 1970-01-01
      • 2013-07-25
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2020-04-10
      相关资源
      最近更新 更多