在WooCommerce中为特定类别的最便宜商品打折

编程入门 行业动态 更新时间:2024-10-11 03:20:20
本文介绍了在WooCommerce中为特定类别的最便宜商品打折的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想根据产品类别对Woocommerce中最便宜的购物车产品打折.根据"产品的购物车折扣在Woocommerce中价格更低" 效果很好的答案代码.

I wound like to discount the cheapest cart item in Woocommerce, based on a product category. Based on "Cart discount for product that cost less in Woocommerce" answer code that works perfectly.

但是如何使其仅适用于特定产品类别.

But how to make it work for a specific product category only.

这个想法是在购物车中有2种商品,并且针对特定商品类别的最便宜商品有折扣.

The idea is to have 2 products in the shopping cart and have a discount on the cheapest item for a specific product category.

推荐答案

已更新-仅限已定义产品类别中的2个项目.

Updated - Limiting to 2 items from the defined product category.

以下将对特定产品类别(将在代码中定义)执行相同的操作:

The following will do the same for a specific product category (to be defined in the code):

add_action('woocommerce_cart_calculate_fees', 'discount_on_cheapest_cart_item', 20, 1 ); function discount_on_cheapest_cart_item( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // Settings $categories = ['tshirts']; // Your product categories (coma separated) $percentage = 10; // 10 % discount // Only for 2 items or more if ( $cart->get_cart_contents_count() < 2 ) return; // Initialising $discount = 0; $item_prices = array(); // Loop though each cart items and set prices in an array foreach ( $cart->get_cart() as $cart_item ) { if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) { $product_prices_excl_tax[] = wc_get_price_excluding_tax( $cart_item['data'] ); } } // We set the fee for 2 items of the defined product category if( count($product_prices_excl_tax) == 2 ) { sort($product_prices_excl_tax); $discount = reset($product_prices_excl_tax) * $percentage / 100; $cart->add_fee( sprintf( __("Discount on cheapest %s"), '('.$percentage.'%)' ), -$discount ); } }

代码进入您的活动子主题(或活动主题)的function.php文件中.应该可以.

Code goes in function.php file of your active child theme (or active theme). It should works.

更多推荐

在WooCommerce中为特定类别的最便宜商品打折

本文发布于:2023-11-30 06:19:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最便宜   中为   类别   商品   WooCommerce

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!