Add a product to cart & go to checkout page on custom button click

I have three products. We are showing three products in list of checkbox. These check boxes are our custom code and below the check boxes we are showing a purchase button.
So when any of the checkbox get checked and the purchase button is clicked we want that product to be added to cart and the chckout page is opened immediately. So can we do that or can we pass product id to checkout page url? I have also tried the following code

var dataString = 'product=430&qty=0&cart_action=add_item';
$.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php?action=mp_update_cart",
data: dataString,
success: function () {
console.log("success");
}
});

It prints the success message in the console but no product is added to the cart.

  • Ash

    Hello antonimike

    Looks like you are familiar with code. I am giving you a sample code that worked for me, I just tested. Please check the code, follow and implement on your site :slight_smile:

    Here is the code:

    add_action( 'wp_head', function() {
    	?>
    	<form action="#" method="post">
    		<label>
    			<input type="checkbox" name="mp_product[]" class="custom_mp_product" value="3458">
    			Prod 2
    		</label>
    		<label>
    			<input type="checkbox" name="mp_product[]" class="custom_mp_product" value="3450">
    			Prod 1
    		</label>
    		<input type="button" id="prod_button" value="Purchase">
    	</form>
    	<script type="text/javascript">
    		jQuery(function($){
    			$( '#prod_button' ).click(function(e){
    				e.preventDefault();
    
    				var products = new Array();
    				$( '.custom_mp_product' ).each(function(){
    					if( $(this).is( ':checked' ) )
    					{
    						products.push( $(this).val() );
    					}
    				});
    
    				var i = 0, done = 0;
    				setInterval(
    					function()
    					{
    						if( ( i + 1 ) == products.length )
    						{
    							done = 1;
    						}
    
    						$.post(
    							'<?php echo admin_url( "admin-ajax.php" ); ?>',
    							{
    								action: 'mp_update_cart',
    								product: products[i],
    								qty: 1,
    								cart_action: 'add_item'
    							},
    							function( response )
    							{
    								if( done == 1 ) window.location.href = "<?php echo get_permalink( mp_get_setting( 'pages->cart' ) ) ?>";
    							}
    						);
    
    						i++;
    
    					}, 2000);
    
    				return false;
    			});
    		});
    	</script>
    	<?php
    } );

    Hope it helps! Please feel free to ask more questions if you have any.

    Have a nice day!

    Cheers,
    Ash