0

I'm working in a ecommerce with wordpresss and woocommerce, im adding to the shop page and category pages buttons that display the sizes for each product. with this code inside the theme function:

function woocommerce_variable_add_to_carts() {
   global $product, $post;
   $variations = $product->get_available_variations();
   $product_sku = $product->get_sku();

   $out = '<ul class="iconic-was-swatches iconic-was-swatches--loop iconic-was-swatches--text-swatch   iconic-was-swatches--square">';
   foreach ($variations as $key => $value) {
    if (!empty($value['attributes'])) {
        foreach ($value['attributes'] as $attr_key => $attr_value) {
            $out .= '<li><a id="'.esc_attr($post->ID).'" data-quantity="1" data-product_id="'.esc_attr($post->ID).'" data-product_sku="'.$product_sku.'" class="iconic-was-swatch iconic-was-swatch--follow iconic-was-swatch--text-swatch add_to_cart_button">';
            $out .= $attr_value . '</a></li>';
        }
    }
}
$out .= '</ul>';
echo $out;
  }

    add_action('woocommerce_before_shop_loop_item_title', 'woocommerce_variable_add_to_carts');

The idea is that when the users click in one of those sizes buttons the product is added to the cart directly in that page (shop page, category page). I made a custom endpoint to solve that from the answer provided here. I call the ajax function in the js file that Contains this:

$('.add_to_cart_button').on('click',function(){

      jQuery.ajax({
            url: WC_VARIATION_ADD_TO_CART.ajax_url,
            type: "POST",
            data: {
                action : "customAdd_to_cart",
                product_id : "697",
                variation_id : "707",
                quantity : 1,
                variation : {
                    size : "s",
                    color: "pink"
                }
            },
            success: function(){
                alert('Ajax Success ');
            }
        });

    });

(i'm using a specific product_id and variation_id for testing) then i add the callback function in the themes function page to add the products to the cart :

function customAddToCart() {
ob_start();
try {

    $product_id        = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $data['product_id'] ) );
    $quantity          = empty( $data['quantity'] ) ? 1 : wc_stock_amount( $data['quantity'] );
    $variation_id      = isset( $data['variation_id'] ) ? absint( $data['variation_id'] ) : '';
    $variations        = $variation_id ? (array) get_variation_data_from_variation_id( $variation_id ) : null;
    $product_status    = get_post_status( $product_id );
    $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $cart_item_data );

    if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations ) && 'publish' === $product_status ) {

        do_action( 'woocommerce_ajax_added_to_cart', $product_id );

        $res = getCartFragments();

    } else {

        $res = array(
            'error' => true
        );

    }

    return $res;

} catch (Exception $e) {
    return new WP_Error('add_to_cart_error', $e->getMessage(), array('status' => 500));
}
}

   add_action( 'wp_ajax_nopriv_woocommerce_add_variation_to_cart', 'customAddToCart' );

all this seems to work fine because doesn't give any error in console but the problems is that the variation Size in not added with the product that is selected just add the product. I dont know why this is happening, i even add an alert in the ajax success function

alert('Ajax Success ');

and that alert is displayed but the data it seems is not been sending like it should.

i want to know what i'm missing in any of this codes or it could be the js file and his location or i need to send another value in the a> builded in the first function above. i have try a lot things but the behavior still the same.

Community
  • 1
  • 1
R. Garcia
  • 57
  • 9
  • 1
    there's nothing in your code to suggest you are even processing the incoming `variation` object, so I'm surprised you only have a problem with `variation.size` - your question makes no mention of a problem with `variation.color` – Jaromanda X Mar 14 '17 at 22:52
  • color is not used has a variation in every product, the users are only allow to select the size. that color inside the ajax call im not really using it just something that it slipped my mind. How should i call the variation size to be recognized by the cart? – R. Garcia Mar 14 '17 at 23:06
  • There's much about your server side that is mysterious to me, I just pointed out that there's nothing in the server side code you posted that even attempts to get any `variation` – Jaromanda X Mar 14 '17 at 23:08
  • i'm using the same code in the answer provided here http://stackoverflow.com/questions/27270880/add-a-variation-to-cart-using-ajax-woocommerce-api, there the ajax call is maded that way. What then i need to add in the function to get the variation of any product? – R. Garcia Mar 14 '17 at 23:17
  • i could get the variation id in the first function when the a> element is build. Could i send from there that data to the ajax and then to the function? – R. Garcia Mar 14 '17 at 23:18

1 Answers1

0

A quick scan over your code and I've noticed that the action you are calling with ajax is not correct. It should be woocommerce_add_variation_to_cart not customAdd_to_cart. Also it is common practice to use wp_send_json (or the more specific wp_send_json_success and wp_send_json_error functions) at the end of your ajax callback function so that you get a readable and sensible response in jQuery. Check out the following link if you have not used it before:

https://codex.wordpress.org/Function_Reference/wp_send_json

Hope this helps.

Kodaloid
  • 1,211
  • 11
  • 19
  • but i'm trying to use a customs add_to_cart function, is the one that i specify in the last code i put in the question, and that function is called customAddTocart(), shouldn't i use that function in the action of the ajax request? – R. Garcia Mar 15 '17 at 16:41