Home › Forums › Product Open Pricing (Name Your Price) for WooCommerce › How to programatically add a product to the cart using a function? › Reply To: How to programatically add a product to the cart using a function?
May 7, 2018 at 7:42 pm #99477
Member
Hello,
Sorry for the long delay.
To add a product with custom price programmatically you would have to do something like this:
// Sets product price add_action( 'woocommerce_before_calculate_totals', function($cart_obj){ if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { return; } foreach ( $cart_obj->get_cart() as $key => $value ) { if ( $value['product_id'] == 6356 ) { $value['data']->set_price( 99 ); } } }, 10, 1 ); // Adds product to cart add_action( 'wp', function () { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { return; } $product_id = 6356; foreach ( WC()->cart->get_cart() as $key => $val ) { $_product = $val['data']; if ( $product_id == $_product->get_id() ) { return true; } } WC()->cart->add_to_cart( $product_id ); } );