simkoG

gtm4wp // custom add to cart button

Feb 25th, 2022 (edited)
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.15 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Custom add to cart button for WooCommerce.
  5.  * This version is compatible with gtm4wp plugin.
  6.  */
  7.  
  8. add_shortcode( 'gtm4wp_add_to_cart', 'gtm4wp_add_to_cart_shortcode' );
  9.  
  10. function gtm4wp_add_to_cart_shortcode( $atts ) {
  11.   $a = shortcode_atts( array(
  12.     'id'        => '',
  13.     'quantity'  => 1,
  14.     'text'      => __( 'Add to cart', 'woocommerce' )
  15.   ), $atts );
  16.  
  17.   if( ! $a['id'] ) {
  18.     return "{ error: missing shortcode arguments }";
  19.   }
  20.  
  21.   global $product;
  22.   $product = new WC_Product( intval( $a['id'] ) );
  23.  
  24.   ob_start();
  25.   ?>
  26.  
  27.   <form class="cart" action="<?php echo esc_url( wc_get_cart_url() . "?add-to-cart={$product->id}&quantity={$a['quantity']}" ); ?>" method="post" enctype="multipart/form-data">
  28.     <button type="submit" name="add-to-cart" value="<?php echo intval( $a['id'] ); ?>" class="single_add_to_cart_button button alt">
  29.       <?php esc_html_e( $a['text'] ); ?>
  30.     </button>
  31.    
  32.     <input type="hidden" name="quantity" value="<?php echo intval( $a['quantity'] ); ?>">
  33.     <?php echo do_action( 'woocommerce_after_add_to_cart_button' ); ?>
  34.   </form>
  35.  
  36.   <?php
  37.   return ob_get_clean();
  38. }
Add Comment
Please, Sign In to add comment