Created
August 26, 2021 20:11
-
-
Save passatgt/a1857fceb31ee22b39d3b9a5e495a4e3 to your computer and use it in GitHub Desktop.
WooCommerce Add To Cart Form Shortcode that supports variable products too
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've added some code to render the form in the right place, especially if you use a visual editor.