Skip to content

Instantly share code, notes, and snippets.

@enru
Last active August 29, 2015 13:59
Show Gist options
  • Select an option

  • Save enru/10721487 to your computer and use it in GitHub Desktop.

Select an option

Save enru/10721487 to your computer and use it in GitHub Desktop.
woocommerce add to cart & adjust price
<?php
// add product to cart with additional data
$woocommerce->cart->add_to_cart($post->ID, $quantity = 1, $variation_id = '', $variation = $entry[1], $cart_item_data = array(
'hire_price'=>123,
));
// make sure additional data sticks in the session
add_action('woocommerce_get_cart_item_from_session', function($cart_item, $values) {
if (isset($values['hire_price'])) {
$cart_item['hire_price'] = $values['hire_price'];
}
return $cart_item;
}, 10, 2);
// dynamically set the price in the cart
add_action('woocommerce_before_calculate_totals', function($cart_object) {
foreach ( $cart_object->cart_contents as $key => $value ) {
if(isset($value['hire_price']) && $value['hire_price']) {
$value['data']->price = $value['hire_price'];
}
}
});
// display the data in the cart item
add_filter('woocommerce_get_item_data', function($other_data, $cart_item) {
if(isset($cart_item['hire_price']) && $cart_item['hire_price']) {
$other_data[] = array('name' => 'Hire Price', 'value' => woocommerce_price($cart_item['hire_price']));
}
return $other_data;
}, 10, 2);
// save the extra data to the order
add_action('woocommerce_order_item_meta', function($item_meta, $cart_item) {
if(isset($cart_item['hire_price']) && $cart_item['hire_price']) {
$item_meta->add('Hire Price', $cart_item['hire_price']);
}
}, 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment