Last active
May 20, 2021 23:25
-
-
Save racmanuel/6c69dc4589d191cc016c8bb047c60c86 to your computer and use it in GitHub Desktop.
Shortcode to add a especific product to cart to any place without reload page - Woocommerce
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
<?php | |
/* Create a Shorcode for custom_ajax_add_to_cart_button to add a Woocommerce Subscription button add to cart to any place*/ | |
if (!function_exists('custom_ajax_add_to_cart_button') && class_exists('WooCommerce')) { | |
function custom_ajax_add_to_cart_button($atts) | |
{ | |
// Shortcode attributes | |
$atts = shortcode_atts(array( | |
'id' => '0', // Product ID | |
'qty' => '1', // Product quantity | |
'text' => '', // Text of the button | |
'class' => '', // Additional classes | |
), $atts, 'ajax_add_to_cart'); | |
if (esc_attr($atts['id']) == 0) { | |
return; | |
} | |
// Exit when no Product ID | |
if (get_post_type(esc_attr($atts['id'])) != 'product') { | |
return; | |
} | |
// Exit if not a Product | |
$product = wc_get_product(esc_attr($atts['id'])); | |
if (!$product) { | |
return; | |
} | |
// Exit when if not a valid Product | |
$classes = implode(' ', array_filter(array( | |
'button', | |
'product_type_' . $product->get_type(), | |
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '', | |
$product->supports('ajax_add_to_cart') ? 'ajax_add_to_cart' : '', | |
))) . ' ' . $atts['class']; | |
$add_to_cart_button = sprintf('<a rel="nofollow" href="%s" %s %s %s class="%s">%s</a>', | |
esc_url($product->add_to_cart_url()), | |
'data-quantity="' . esc_attr($atts['qty']) . '"', | |
'data-product_id="' . esc_attr($atts['id']) . '"', | |
'data-product_sku="' . esc_attr($product->get_sku()) . '"', | |
esc_attr(isset($classes) ? $classes : 'button'), | |
esc_html(empty(esc_attr($atts['text'])) ? $product->add_to_cart_text() : esc_attr($atts['text'])) | |
); | |
return $add_to_cart_button; | |
} | |
add_shortcode('ajax_add_to_cart', 'custom_ajax_add_to_cart_button'); | |
} | |
/* | |
* Use of Shorcode | |
* echo do_shortcode("[ajax_add_to_cart id='THE ID OF YOUR PRODUCT OR SUBSCRIPTION' text='¡Try the Subscription Standard!' qty='1' class='']"); | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment