Created
April 11, 2023 12:47
-
-
Save kartick14/5e56d41d517a898b252be5d347b7dc77 to your computer and use it in GitHub Desktop.
Woocommerce product customization with additional data passing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ------------------------- ADD TO CART section start --------------------- */ | |
add_action('wp_ajax_nopriv_add_to_cart_ajax', 'add_to_cart_ajax_func'); | |
add_action('wp_ajax_add_to_cart_ajax', 'add_to_cart_ajax_func'); | |
function add_to_cart_ajax_func(){ | |
//print_r($_POST); | |
$product_id = $_POST['product_id']; | |
$product_quantity = $_POST['product_quantity']; | |
$total_price = $_POST['total_price']; | |
$product_addons = $_POST['product_addons']; | |
if(!empty($product_addons)){ | |
foreach ($product_addons as $key => $value) { | |
$explodeArr = explode(':',$value); | |
$arrKey = $explodeArr[0]; | |
$prodAddOns[$arrKey] = $explodeArr[1]; | |
} | |
} | |
WC()->cart->add_to_cart( $product_id, $product_quantity, 0, array(), array('add_size' => $prodAddOns, 'misha_custom_price' => ($total_price / $product_quantity))); | |
$return = array( | |
'status' => true | |
); | |
wp_send_json($return); | |
exit(); | |
} | |
// Display custom cart item meta data (in cart and checkout) | |
add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_meta_data', 10, 2 ); | |
function display_cart_item_custom_meta_data( $item_data, $cart_item ) { | |
if ( isset($cart_item['add_size']) ) { | |
foreach ($cart_item['add_size'] as $skey => $svalue) { | |
$item_data[] = array( | |
'key' => $skey, | |
'value' => $svalue, | |
); | |
} | |
} | |
return $item_data; | |
} | |
// Save cart item custom meta as order item meta data and display it everywhere on orders and email notifications. | |
add_action( 'woocommerce_checkout_create_order_line_item', 'save_cart_item_custom_meta_as_order_item_meta', 10, 4 ); | |
function save_cart_item_custom_meta_as_order_item_meta( $item, $cart_item_key, $values, $order ) { | |
if ( isset($values['add_size']) ) { | |
foreach ($values['add_size'] as $skey => $svalue) { | |
$item->update_meta_data( $skey, $svalue); | |
} | |
} | |
} | |
add_action( 'woocommerce_before_calculate_totals', 'rudr_custom_price_refresh' ); | |
function rudr_custom_price_refresh( $cart_object ) { | |
foreach ( $cart_object->get_cart() as $item ) { | |
if( array_key_exists( 'misha_custom_price', $item ) ) { | |
$item[ 'data' ]->set_price( $item[ 'misha_custom_price' ] ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment