[英]Add a percent fee to WooCommerce per product, based on category
我是新来的,尽管我几个月来一直在使用该网站,以寻求其他问题的帮助。
我正在尝试通过以下方式在woocommerce中添加费用:
该站点必须检查购物车,找到符合类别ID的产品,计算每种产品的费用百分比,对它们进行汇总并收取费用。
到目前为止,我已经设法检查了购物车,找到了符合类别的产品(获取数量)并乘以固定费用乘以金额。
如您所见,如果我有3个产品符合标准(类别ID),分别为£50,£40和£30,则费用将为3 * 10(固定费用为10)。
我真正想要的是该网站计算这些产品的费用百分比(50 * 10、40 * 10、30 * 10)并将其加起来(500 + 400 + 300)。 显然,并非所有产品的价格都相同。
这是我的代码:
function df_add_handling_fee( $cart_object ) {
global $woocommerce;
$specialfeecat = 61; // category id for the special fee
$spfee = 0.00; // initialize special fee
$spfeeperprod = 10; //special fee per product
//Getting Cart Contents.
$cart = $woocommerce->cart->get_cart();
//Calculating Quantity
foreach($cart as $cart_val => $cid){
$qty += $cid['quantity'];
}
foreach ( $cart_object->cart_contents as $key => $value ) {
$proid = $value['product_id']; //get the product id from cart
$quantiy = $value['quantity']; //get quantity from cart
$itmprice = $value['data']->price; //get product price
$terms = get_the_terms( $proid, 'product_cat' ); //get taxonomy of the products
if ( $terms && ! is_wp_error( $terms ) ) :
foreach ( $terms as $term ) {
$catid = $term->term_id;
if($specialfeecat == $catid ) {
$spfee = $spfee + $quantiy * $spfeeperprod;
}
}
endif;
}
if($spfee > 0 ) {
$woocommerce->cart->add_fee( 'Handling Fee', $spfee, true, 'standard' );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'df_add_handling_fee' );
谢谢!
希望这会有所帮助:
产品A-类别1 ///产品B-类别2 ///产品C-类别3 ////产品D-类别1
我的购物车=产品A的2个,产品B的3个,产品C的1个和产品D的4个
我想添加一笔费用,计算出我有1类和2类中的7件商品,并且每件产品的固定价格为5美元。
我发现在线下面的代码可能更容易...不幸的是,我已经购买了几个插件,但是它们不能满足我的需求。
add_action( 'woocommerce_cart_calculate_fees','custom_applied_fee');
function custom_applied_fee() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set HERE your categories (can be an ID, a slug or the name… or an array of this)
$category1 = 'plain';
$category2 = 'plywood';
// variables initialisation
$fee = 0;
// Iterating through each cart item
foreach(WC()->cart->get_cart() as $cart_item){
// Get the product object
$product = new WC_Product( $cart_item['product_id'] );
$quantiy = $value['quantity']; //get quantity from cart
// Initialising variables (in the loop)
$cat1 = false; $cat2 = false;
// ## CALCULATIONS ## (Make here your conditional calculations)
$quantity = GET TOTAL QUANTITY OF ALL ITEMS IN PREVIOUSLY SPECIFIED CATEBORIES
if($quantity <= 1){
$fee += 10 * $quanity;
} elseif($quantity > 1 && $dimention <= 9){
$fee += 5 * $quanity;
} elseif($dimention > 10){
$fee += 1 * $quanity;
}
}
// Adding the fee
if ( $fee != 0 )
WC()->cart->add_fee( $fee_text, $fee, true );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.