Я пытаюсь применить плату в зависимости от категории продукта и длины продукта.
Если продукт относится к определенной категории и его длина меньше 30 м, я хочу взимать плату за снижение цены за продукт (стоимость резки рулона напольного покрытия).
У меня есть работающая функция, которая добавляет цену снижения в определенную категорию, но я не могу понять, как сделать ее условной, поэтому она добавляет плату только в том случае, если длина предмета меньше 30 м.
Пожалуйста, смотрите две версии, которые я пробовал ниже:
Функция 1: Приведенный ниже код работает без условия длины, поэтому добавляет плату к каждому товару в корзине с определенной категорией.
// Add cut price to category flotex
function woo_add_cart_fee() {
$category_ID = '83'; // Flotex Category is 83
global $woocommerce;
$cpfee = 0.00; // initialize special fee
//Getting Cart Contents.
$cart = $woocommerce->cart->get_cart();
//Calculating Quantity in cart
foreach($cart as $cart_val => $cid){
$qty += $cid['quantity'];
}
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
// Get the terms, i.e. category list using the ID of the product
$terms = get_the_terms( $values['product_id'], 'product_cat' );
// Because a product can have multiple categories, we need to iterate through the list of the products category for a match
foreach ($terms as $term) {
// 83 is the ID of the category for which we want to remove the payment gateway
if ($term->term_id == $category_ID){
$cutprice = 30;
}
$cpfee = $qty * $cutprice;
}
$woocommerce->cart->add_fee('Cut Price', $cpfee, $taxable = true, $tax_class = 'standard');
}
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
?>
Функция 2: Приведенный ниже код является попыткой добавить правило условной длины, но оно не работает. Он всегда возвращает либо 0, либо взимает 30 за каждый элемент, даже если длина равна 30.
// Add cut price to category flotex
function woo_add_cart_fee() {
$category_ID = '83'; // Flotex Category is 83
global $woocommerce;
$cpfee = 0.00; // initialize special fee
$qty = 0;
$cutpricesmall = 0;
//Getting Cart Contents.
$cart = $woocommerce->cart->get_cart();
//Calculating Quantity in cart
foreach($cart as $cart_val => $cid){
$qty += $cid['quantity'];
}
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
$product = $values['data'];
$length = $product->get_length();
// Get the terms, i.e. category list using the ID of the product
$terms = get_the_terms( $values['product_id'], 'product_cat' );
if ( $length < 29 ) {
// Because a product can have multiple categories, we need to iterate through the list of the products category for a match
foreach ($terms as $term) {
// 83 is the ID of the category for which we want to remove the payment gateway
if ($term->term_id == $category_ID){
$cutprice = 30;
}
}
} elseif ( $length > 29 ){
foreach ($terms as $term) {
// 83 is the ID of the category for which we want to remove the payment gateway
if ($term->term_id == $category_ID){
$cutpricesmall = 0;
}
}
}
$cpfee = $qty * ($cutprice + $cutpricesmall);
$woocommerce->cart->add_fee('Cut Price', $cpfee, $taxable = true, $tax_class = 'standard');
}
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
Любые советы с этим будут действительно оценены.
Ваш код содержит некоторые ошибки или может быть оптимизирован:
$woocommerce;
не обязательноget_the_terms()
заменяется на has_term()
foreach
, а 1 должно хватить.Итак, вы получаете:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Specific categories: the term name/term_id/slug. Several could be added, separated by a comma
$categories = array( 83, 'categorie-1' );
// Settings
$cut_price = 30;
$length = 30;
// Initialize
$cp_fee = 0;
// Gets cart contents
foreach ( $cart->get_cart_contents() as $cart_item ) {
// Has certain category
if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
// Get length
$product_length = $cart_item['data']->get_length();
// NOT empty and less than
if ( ! empty ( $product_length ) && $product_length < $length ) {
// Get quantity
$quantity = $cart_item['quantity'];
// Addition to the total
$cp_fee += $cut_price * $quantity;
}
}
}
// Greater than
if ( $cp_fee > 0 ) {
// Add fee
$cart->add_fee( __( 'Cut Price', 'woocommerce' ), $cp_fee, true );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
Примечание:, если не следует учитывать количество продукта на продукт
Заменять:
// NOT empty and less than
if ( ! empty ( $product_length ) && $product_length < $length ) {
// Get quantity
$quantity = $cart_item['quantity'];
// Addition to the total
$cp_fee += $cut_price * $quantity;
}
С:
// NOT empty and less than
if ( ! empty ( $product_length ) && $product_length < $length ) {
// Addition to the total
$cp_fee += $cut_price;
}