Skip to content

Instantly share code, notes, and snippets.

@olar94
Created September 4, 2018 14:11
Show Gist options
  • Save olar94/e9f6c2c529602f12278a81b25045dd8b to your computer and use it in GitHub Desktop.
Save olar94/e9f6c2c529602f12278a81b25045dd8b to your computer and use it in GitHub Desktop.
Add product to cart and setting up custom price | woocommerce
global $woocommerce;
$woocommerce->cart->empty_cart(); //чистим
$custom_price = $price; //$price - переменная с ценой
$product_id = 11963; //id любого товара
$quantity = 1; //кол-во
$cart_item_data = array('custom_price' => $custom_price);
$woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
$woocommerce->cart->calculate_totals();
$woocommerce->cart->set_session();
$woocommerce->cart->maybe_set_cart_cookies();
----------Bottom code insert to functions.php----------
add_filter( 'woocommerce_cart_ready_to_calc_shipping', 'delshipping_calc_in_cart', 1000 );
function woocommerce_custom_price_to_cart_item( $cart_object ) {
if( !WC()->session->__isset( "reload_checkout" )) {
foreach ( $cart_object->cart_contents as $key => $value ) {
if( isset( $value["custom_price"] ) ) {
//for woocommerce version lower than 3
//$value['data']->price = $value["custom_price"];
//for woocommerce version +3
$value['data']->set_price($value["custom_price"]);
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'woocommerce_custom_price_to_cart_item', 1000 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment