I’ve been rebuilding my WooCommerce plugin demos to make them easier to use and understand. For my WooCommerce Delivery Slots demo, I decided to direct people straight to the checkout page. As such, I found myself needing to programatically add a few items to the cart when the page is loaded. I decided to hook into the wp action, as I could then check which page was being loaded. I then used some WooCommerce methods to add some items to the cart:
1234567891011121314151617
/** * Add items to cart on loading checkout page. */function iconic_add_to_cart() {if ( ! is_page( ‘checkout’ ) ) {return;}if ( ! WC()->cart->is_empty() ) {return;}WC()->cart->add_to_cart( 54, 1 );WC()->cart->add_to_cart( 22, 2 );}add_action( ‘wp’, ‘iconic_add_to_cart’ );
Firstly, I check to see if it’s the checkout page. If it is, I then check to see if the cart is empty. Finally, if the cart was empty I add 2 products to the cart programatically.
The method we want to focus on here is WC()->cart->add_to_cart();.
The function accepts 5 parameters:
The first parameter is the $product_id. For simple products, assuming we only want to add 1, we could just enter the product ID and be
Source: https://managewp.org/articles/15993/programatically-add-products-to-your-woocommerce-cart
source https://williechiu40.wordpress.com/2017/08/29/programatically-add-products-to-your-woocommerce-cart/
No comments:
Post a Comment