php - 根据 Woocommerce 中的其他购物车项目数自动将特定产品添加到购物车
问题描述
我正在尝试根据我在购物车中有多少产品将名为(送货费)的产品添加到购物车中。
购物车示例:
产品 A(数量 5)
产品 B(数量 2)
产品 C(数量 4)
运费(数量 3) **这是 3,因为这是在添加了运费产品。
我的代码有问题:
/* Function to get total Products (line items) not qty of each */
function count_item_in_cart() {
global $woocommerce;
$counter = 0;
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
$counter++;
}
return $counter;
}
/* Add DC (Delivery Charge Product) to Cart based on qty */
add_action( 'template_redirect', 'delivery_charge_add_product_to_cart' );
function delivery_charge_add_product_to_cart() {
/* Establish Product Delivery Charge Product ID */
global $woocommerce;
$product_id = 4490; /* Product ID to add to cart */
$quantity = count_item_in_cart();
if ($quantity > 0) {
WC()->cart->add_to_cart( $product_id, $quantity);
}
}
它总是返回一个更高的数字。我认为这是计算每个产品的数量,而不是实际产品项目。
任何帮助,将不胜感激!
解决方案
每次将产品添加到购物车时,以下代码将自动将您的附加产品“运费”添加/更新到购物车,并将处理所有可能的情况:
add_action( 'woocommerce_before_calculate_totals', 'add_delivery_charge_to_cart', 10, 1 );
function add_delivery_charge_to_cart( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$dcharge_id = 4490; // Product Id "Delivery charge" to be added to cart
$items_count = 0; // Initializing
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Check if "Delivery charge" product is already in cart
if( $cart_item['data']->get_id() == $dcharge_id ) {
$dcharge_key = $cart_item_key;
$dcharge_qty = $cart_item['quantity'];
}
// Counting other items than "Delivery charge"
else {
$items_count++;
}
}
// If product "Delivery charge" is in cart, we check the quantity to update it if needed
if ( isset($dcharge_key) && $dcharge_qty != $items_count ) {
$cart->set_quantity( $dcharge_key, $items_count );
}
// If product "Delivery charge" is not in cart, we add it
elseif ( ! isset($dcharge_key) && $items_count > 0 ) {
$cart->add_to_cart( $dcharge_id, $items_count );
}
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。测试和工作。
推荐阅读
- python - Python 需要帮助理解位和字节操作的意外行为
- django - order_by() 和 latest() 返回不同的查询集值
- php - 如何使用 Capsule 和 MySQL 两种方式查询 `jump condition` 表数据?
- apache-spark - 我们可以在 GKE 上的不同节点池上安排 spark 驱动程序和执行程序吗?
- spring-security - Keycloak spring-security Adapter: antMatchers("/**").authenticated() 没有启动认证过程
- javascript - 如何在文本和表格之间切换?
- hadoop - HDFS 的 HUE 和 Job Scheduler 安装
- wordpress - Wordpress 添加具有 3 个以上子菜单的管理菜单
- java - 尝试使用java从webapp在datalake中创建文件
- c# - 如何为组合框设置默认值?