在 WooCommerce 中以编程方式添加特定产品后将价格设置为零

问题描述 投票:0回答:1

我通过从 Ajax 检索的产品 ID 将产品添加到购物车,但由于某种原因,我无法将自定义价格添加到添加到购物车的产品中。

我尝试添加产品 id 作为全局变量以在其他函数中使用变量,但无法将产品设置为 0。这就是我的代码最终的样子。

JS:

<script>
 const selectedProductId = getProdVal(randomDegree);
  const isProductInCart = isProductAlreadyInCart(selectedProductId);

  if (!productAdded && !isProductInCart) {
    jQuery.ajax({
      url: <?php echo json_encode(admin_url('admin-ajax.php')) ?>,
      type: 'POST',
      data: {
        action: 'add_product_to_cart',
        product_id: selectedProductId,
      },
      success: function(response) {
        console.log(response);
        productAdded = true;
        spinBtn.disabled = false;
      },
      error: function(error) {
        console.error(error);
        spinBtn.disabled = false;
      }
    });
    jQuery.ajax({
      url: <?php echo json_encode(admin_url('admin-ajax.php')) ?>,
      type: 'POST',
      data: {
        action: 'custom_set_cart_item_price',
        product_id: selectedProductId,
      },
      success: function(response) {
        console.log(response);
      },
      error: function(error) {
        console.error(error);
      }
    });
  }
</script>

PHP:

function add_product_to_cart()
{
  if (isset($_POST['product_id'])) {
    $product_id = intval($_POST['product_id']);
    if (!in_array($product_id, get_product_ids_from_cart())) {
      WC()->cart->add_to_cart($product_id, 1, 0, [], []);
    }
    echo json_encode(array('success' => true, 'message' => 'Product added to cart.'));
  } else {
    echo json_encode(array('success' => false, 'message' => 'Product ID is missing.'));
  }

  exit;
}
add_action('wp_ajax_add_product_to_cart', 'add_product_to_cart');
add_action('wp_ajax_nopriv_add_product_to_cart', 'add_product_to_cart');
add_action('wp_ajax_custom_set_cart_item_price', 'custom_set_cart_item_price');
add_action('wp_ajax_nopriv_custom_set_cart_item_price', 'custom_set_cart_item_price');
function custom_set_cart_item_price($cart) {
  if (isset($_POST['product_id'])) {
    $product_id = intval($_POST['product_id']);
    $custom_price = 0.00; 
    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        if ($cart_item['product_id'] == $product_id) {
          
            $cart_item['data']->set_price($custom_price);
            $cart->cart_contents[$cart_item_key] = $cart_item;
        }
    }
  }
}
add_action('woocommerce_before_calculate_totals', 'custom_set_cart_item_price');
php wordpress woocommerce product cart
1个回答
0
投票

当您将产品添加到购物车时,方法

add_to_cart()
返回购物车项目密钥,下面我们将在WC_Session变量中设置该购物车项目密钥,我们将在
woocommerce_before_calculate_totals
挂钩中使用该变量来检索正确的购物车项目将其价格更改为零。

假设您的 jQuery 代码有效,并通过 Ajax 发送要添加的产品 ID:

<script>
const selectedProductId = getProdVal(randomDegree);
const isProductInCart = isProductAlreadyInCart(selectedProductId);

if (!productAdded && !isProductInCart) {
    jQuery.ajax({
        url: <?php echo json_encode(admin_url('admin-ajax.php')) ?>,
        type: 'POST',
        data: {
            action: 'custom_add_to_cart', // <== Renamed
            product_id: selectedProductId,
        },
        success: function(response) {
            console.log(response);
            productAdded = true;
            spinBtn.disabled = false;
        },
        error: function(error) {
            console.error(error);
            spinBtn.disabled = false;
        }
    });
}
</script>

PHP:

add_action('wp_ajax_custom_add_to_cart', 'custom_add_to_cart');
add_action('wp_ajax_nopriv_custom_add_to_cart', 'custom_add_to_cart');
function custom_add_to_cart() {
    if (isset($_POST['product_id']) && $_POST['product_id'] > 0 ) {
        $product_id = intval($_POST['product_id']);

        if (!in_array($product_id, get_product_ids_from_cart())) {
            // Get previous added products (if any) from WC_Session variable
            $items_keys = (array) WC()->session->get('zero_price_items'); 
            
            $cart_item_key = WC()->cart->add_to_cart($product_id, 1); // Add product 
            $items_keys[$cart_item_key] = $product_id; // add the key to the array

            // Save cart item key in a WC_Session variable
            WC()->session->set('zero_price_items', $items_keys );

            echo json_encode(array('success' => true, 'message' => 'Product added to cart.'));
        } else {
            echo json_encode(array('success' => true, 'message' => 'Product already in cart.'));
        }
    } else {
        echo json_encode(array('success' => false, 'message' => 'Product ID is missing.'));
    }
    wp_die();
}

// Change cart item price
add_action('woocommerce_before_calculate_totals', 'custom_set_cart_item_price');
function custom_set_cart_item_price( $cart ) {
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $items_keys = (array) WC()->session->get('zero_price_items'); // Get the WC_Session variable data

    // Loop through cart items
    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        // Check if the product has been added via custom ajax
        if ( isset($items_keys[$cart_item_key]) && $items_keys[$cart_item_key] == $cart_item['product_id'] ) {
            $cart_item['data']->set_price(0);
        }
    }
}

// For mini cart displayed price
add_action( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 2 );
function filter_cart_item_price( $price_html, $cart_item, $cart_item_key ) {
    global $product;

    $items_keys = (array) WC()->session->get('zero_price_items'); // Get the WC_Session variable data

    // Check if the product has been added via custom ajax
    if ( isset($items_keys[$cart_item_key]) && $items_keys[$cart_item_key] == $cart_item['product_id'] ) {
        return wc_price( 0 );
    }
    return $price_html;
}

代码位于tour子主题的functions.php文件中(或插件中)。应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.