How to programatically add a product to the cart using a function?

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #99476
    teamcoltra
    Member

    Hey! I love this plugin and it helps a lot. Right now I’m working on allowing my customers to add a donation to charity at the checkout page and thought the easiest way would be to just incorporate a pay what you want product and allow people to set their own amount.

    I was wondering if, perhaps, you could help me figure out how to programatically add a pay-what-you-want product to the cart using a function?

    WC()->cart->add_to_cart( $product_id );

    but I don’t know how to set the cost field? I’m sure I’ll need quite a bit more but any help you can give will be great, thanks!

    #99477

    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 );
    } );
Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘Product Open Pricing (Name Your Price) for WooCommerce’ is closed to new topics and replies.