Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hamidrezayazdani/7374e4dd58f56ecd5e4c96737009b6b7 to your computer and use it in GitHub Desktop.
Save hamidrezayazdani/7374e4dd58f56ecd5e4c96737009b6b7 to your computer and use it in GitHub Desktop.
Add single product price for variable boxed products in the cart and checkout
<?php
/**
* prerequisites:
* You must define products as variables. One variation for single purchase and one variation for box purchase.
*
* You can change the name of the box purchase attribute in the code below. (the 'box-capacity' variable).
* For each variation, you set one equal to the number 1 for the other variation equal to the number in each box.
*
* Copy the following code into the functions.php file of the theme/child theme.
*/
/**
* Check product is/n't boxed
*
* @param $product
*
* @return bool
*/
function ywp_check_product_is_boxed_type( $product ) {
$box_capacity_attr = 'box-capacity';
return (int) $product->get_attribute( $box_capacity_attr ) > 1;
}
/**
* Calculate individual product of boxed products
*
* @param $product
* @param $price
* @param $quantity
*
* @return mixed|string
*/
function ywp_calc_single_price_of_boxed( $product, $price, $quantity = 1 ) {
$box_capacity_attr = 'box-capacity';
$box_capacity = (int) $product->get_attribute( $box_capacity_attr );
$cleaned_price = preg_replace( '/\D+/', '', $price );
return 2 < $box_capacity ? $product_price : wc_price( ( $cleaned_price / $quantity ) / $box_capacity );
}
/**
* Change product item price text in cart and checkout
*
* @param $product_price
* @param $product
*
* @return mixed|string
*/
function ywp_add_unit_price_to_cart_item_price( $product_price, $product ) {
$is_boxed = ywp_check_product_is_boxed_type( $product );
if ( ! $is_boxed ) {
return $product_price;
}
$single_price = ywp_calc_single_price_of_boxed( $product, $product_price );
return sprintf(
'%s<span class="signle-price-of-boxed">قیمت هر عدد: $s</span>',
$product_price,
$single_price,
);
}
add_filter( 'woocommerce_cart_product_price', 'ywp_add_unit_price_to_cart_item_price', 10, 2 );
/**
* Change product subtotal text in cart and checkout
*
* @param $product_subtotal
* @param $product
* @param $quantity
* @param $cart
*
* @return mixed|string
*/
function ywp_add_unit_price_to_cart_item_subtotal( $product_subtotal, $product, $quantity, $cart ) {
$is_boxed = ywp_check_product_is_boxed_type( $product );
if ( ! $is_boxed ) {
return $product_subtotal;
}
$single_price = ywp_calc_single_price_of_boxed( $product, $product_subtotal, $quantity );
return sprintf(
'%s<span class="signle-price-of-boxed">قیمت هر عدد: $s</span>',
$product_subtotal,
$single_price,
);
}
add_filter( 'woocommerce_cart_product_subtotal', 'ywp_add_unit_price_to_cart_item_subtotal', 10, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment