【问题标题】:Check if customer has purchased something and add product to cart in WooCommerce检查客户是否购买了东西并将产品添加到 WooCommerce 中的购物车
【发布时间】:2021-05-29 08:46:04
【问题描述】:

以下代码在 WooCommerce 中自动将产品添加到购物车:

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 64;
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
}

答案Checking if customer has already bought something in WooCommerce 允许使用自定义条件函数has_bought() 检查用户是否已经购买。

所以我想要检查客户之前是否订购过并且:

  • 如果这是他们的第一个订单,请将产品 A 强制放入购物车或
  • 如果他们已经购买了一次或多次,则强制产品 B 进入 购物车

但我没有找到在我的代码中使用它的方法。

任何帮助将不胜感激。

【问题讨论】:

    标签: php wordpress woocommerce product cart


    【解决方案1】:

    下面的代码使用the custom function has_bought()。它会自动将新客户和已确认客户的不同产品添加到购物车:

    add_action( 'template_redirect', 'add_product_to_cart_conditionally' );
    function add_product_to_cart_conditionally() {
        if ( is_admin() )  return; // Exit
    
        // Below define the product Id to be added:
        $product_A = 37; // <== For new customers that have not purchased a product before (and guests)
        $product_B = 53; // <== For confirmed customers that have purchased a product before
    
        $product_id = has_bought() ? $product_B : $product_A;
    
        // If cart is empty
        if( WC()->cart->is_empty() ) {
            WC()->cart->add_to_cart( $product_id ); // Add the product
        }
        // If cart is not empty
        else {
            // Loop through cart items (check cart items)
            foreach ( WC()->cart->get_cart() as $item ) {
                // Check if the product is already in cart
                if ( $item['product_id'] == $product_id ) {
                    return; // Exit if the product is in cart
                }
            }
            // The product is not in cart: We add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
    

    代码进入活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    相关:Checking if customer has already bought something in WooCommerce

    【讨论】:

      猜你喜欢
      • 2014-11-21
      • 2016-12-16
      • 2021-08-22
      • 2014-02-06
      • 1970-01-01
      • 2019-02-20
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多