【问题标题】:restrict access for some products if user haven't meta如果用户没有元数据,则限制对某些产品的访问
【发布时间】:2015-12-29 06:45:25
【问题描述】:

我们有一家商店,可以使用 WordPress 和 WooCommerce。

几乎每个产品都会调用 api,用于更新客户端数据库。但是,我们不需要向没有指定“club_card”元数据的用户销售产品。

有没有办法检查用户是否指定了此类元数据,如果没有,则限制购买产品的访问权限

【问题讨论】:

  • 这个问题太笼统了。尝试自己进行一些研究,然后提出更具体的问题!
  • 对 API 的引用和更新客户端数据库令人困惑。但最后一句话非常具体:如何限制具有特定用户元的用户购买特定产品。

标签: php wordpress woocommerce


【解决方案1】:

您无需等到项目被添加后再重新定向。您可以验证是否可以在 woocommerce_add_to_cart_validation 过滤器上添加项目。您的其余逻辑非常有效。

add_filter( 'woocommerce_add_to_cart_validation', 'so_34505885_add_to_cart_validation' ), 10, 6 );
function so_34505885_add_to_cart_validation( $passed_validation, $product_id, $product_quantity, $variation_id = '', $variations = array(), $cart_item_data = array() ) {

        // If product tagged as for club members
        if (has_term( 'club-only', 'product_tag', $product_id )){
            $current_user = wp_get_current_user();
            if ( !$current_user || $current_user->club_card_number == ''){
                wc_add_notice( sprintf( __( 'You must be a club member to purchase this product.', 'your-plugin-textdomain' ), $mnm_item->get_title() ), 'error' );
                    $passed_validation = false;
            }
        }
        return $passed_validation;
}

或者甚至更好的是,您甚至可以通过切换产品是否可购买来完全阻止添加到购物车按钮甚至对无法购买的商品起作用。

add_filter( 'woocommerce_is_purchasable', 'so_34505885_is_purchasable' ), 10, 2 );
function so_34505885_is_purchasable( $purchasable, $product_id ) {

        // If product tagged as for club members
        if (has_term( 'club-only', 'product_tag', $product_id )){
            $current_user = wp_get_current_user();
            if ( !$current_user || $current_user->club_card_number == ''){
                wc_add_notice( sprintf( __( 'You must be a club member to purchase this product.', 'your-plugin-textdomain' ), $mnm_item->get_title() ), 'error' );
                    $purchasable = false;
            }
        }
        return $purchasable;
}

【讨论】:

  • 太棒了!谢谢你!你的解决方案看起来比我的更符合逻辑;)
【解决方案2】:

最后我使用了这个解决方案:

我们在woocommerce_add_to_cart钩子上添加了新动作

add_action('woocommerce_add_to_cart', 'on_add_to_cart_check_club_info', 10,2);

并检查每件产品,如果有标签表明该产品仅供俱乐部用户使用:

function on_add_to_cart_check_club_info($cart_item_key, $product_id)
{
    // If product tagged as for club members
    if (has_term( 'club-only', 'product_tag', $product_id ))
    {
        $current_user = wp_get_current_user();
        if (!$current_user || $current_user->club_card_number == '')
        {
            // Drop to the same page if user haven't specified club card number
            header('Location: '.get_permalink($product_id));
            break;
        }
    }
}

【讨论】:

  • 看我的回答。这两个选项都提供了更好的用户体验。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 2012-05-31
  • 2012-06-16
  • 2013-04-04
  • 1970-01-01
相关资源
最近更新 更多