Add a product to the cart programmatically in WooCommerce

/**
 * Adds a product to the cart.
 *
 * Should not be called before the `wp_loaded` action.
 *
 * @see https://wpcodebook.com/woocommerce-add-product-to-cart-programmatically/
 * @see https://github.com/woocommerce/woocommerce/blob/9.3.3/plugins/woocommerce/includes/class-wc-cart.php#L1025
 */
function wpcodebook_add_to_cart( $product_or_variation_id, $quantity = 1 ) {
	if ( function_exists( 'WC' ) ) {
		WC()->cart->add_to_cart( $product_or_variation_id, $quantity );
	}
}

Leave a Comment