WordPress: creare un configuratore per i prodotti di WooCommerce: la tecnica completa

WordPress: creare un configuratore per i prodotti di WooCommerce: la tecnica completa

Partendo dalla manipolazione degli URL di WooCommerce possiamo creare un configuratore per i suoi prodotti.

In functions.php avremo il seguente shortcode:


function my_wc_shortcode( $atts, $content = null ) {
  extract( shortcode_atts( array (
    'id' => 140,
    'variation' => 141
  ), $atts ) );

  global $woocommerce;
  $cart_url = $woocommerce->cart->get_cart_url();

  $link_url = $cart_url . '?add-to-cart=' . $id . '&variation_id=' . $variation;

  $prod = new WC_Product( $id );
  $attrs = $prod->get_attributes();
  $parts = array();

  foreach( $attrs as $attr ) {
    $parts[] = 'attribute_' . $attr['name'] . '={' . $attr['name'] . '}';
  }

  $link_url .= '&' . implode( '&', $parts );
  $html = '<a href="' . $link_url . '" class="my-wc-btn">Salva e acquista</a>';

  return $html;

}

add_shortcode( 'my-wc-btn', 'my_wc_shortcode' );

A questo punto con jQuery dobbiamo sostituire i segnaposto dell'URL con i valori scelti dall'utente:


$( ".my-wc-btn" ).click(function() {
  var $btn = $( this );
  var url = this.href;
  var choice = $( "option:selected", ".color" ).val();
  var href = url.replace( "{pa_color}", choice );
  window.location = href;
  return false;
});

Torna su