Skip to content

Instantly share code, notes, and snippets.

@passatgt
Created August 26, 2021 20:11
Show Gist options
  • Save passatgt/a1857fceb31ee22b39d3b9a5e495a4e3 to your computer and use it in GitHub Desktop.
Save passatgt/a1857fceb31ee22b39d3b9a5e495a4e3 to your computer and use it in GitHub Desktop.
WooCommerce Add To Cart Form Shortcode that supports variable products too
add_shortcode( 'add-to-cart-form', function($atts) {
global $post;
//Get shortcode attributes
$a = shortcode_atts( array(
'id' => 0
), $atts );
//Find the product and set it to global
$product_data = get_post( $a['id'] );
$product = is_object( $product_data ) && in_array( $product_data->post_type, array( 'product', 'product_variation' ), true ) ? wc_setup_product_data( $product_data ) : false;
//If its not a product, return nothing
if ( ! $product ) {
return '';
}
//This will render the add to cart form
do_action( 'woocommerce_' . $product->get_type() . '_add_to_cart' );
//Reset global $post
wc_setup_product_data( $post );
});
@zoogits
Copy link

zoogits commented Nov 6, 2023

I've added some code to render the form in the right place, especially if you use a visual editor.

// This will render the add to cart form
ob_start();
do_action( 'woocommerce_' . $product->get_type() . '_add_to_cart' );
$add_to_cart_content = ob_get_clean();
return $add_to_cart_content;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment