php - Updating WooCommerce cart after adding a variable product (AJAX) -
i overriding ajax function add product using woocommerce can send attributes cart (which doesn't work out of box).
i followed instructions on update woocommerce cart after adding variable product via ajax - want - doesn't work completely.
everything when logged out. when log wordpress php override doesn't work/gets ignored. no errors , no product added cart. tried many different approaches, nothing helps.
function ajax_add_to_cart_script() { $vars = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ); wp_enqueue_script( 'wc-variation-add-to-cart', get_template_directory_uri() . '/js/jquery.add-to-cart.js', array( 'jquery' ), null, true); wp_localize_script( 'wc-variation-add-to-cart', 'wc_variation_add_to_cart', $vars ); } add_action( 'wp_enqueue_scripts', 'ajax_add_to_cart_script' ); add_action( 'wp_ajax_nopriv_woocommerce_add_variation_to_cart', 'so_27270880_add_variation_to_cart' ); function so_27270880_add_variation_to_cart() { ob_start(); $product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_post['product_id'] ) ); $quantity = empty( $_post['quantity'] ) ? 1 : wc_stock_amount( $_post['quantity'] ); $variation_id = isset( $_post['variation_id'] ) ? absint( $_post['variation_id'] ) : ''; $variations = ! empty( $_post['variation'] ) ? (array) $_post['variation'] : ''; $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity ); if ( $passed_validation && wc()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations ) ) { do_action( 'woocommerce_ajax_added_to_cart', $product_id ); if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) { wc_add_to_cart_message( $product_id ); } // return fragments wc_ajax::get_refreshed_fragments(); } else { // if there error adding cart, redirect product page show errors $data = array( 'error' => true, 'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ) ); wp_send_json( $data ); } die(); }
i making sure add_action( 'wp_ajax_nopriv_woocommerce_add_variation_to_cart', 'so_27270880_add_variation_to_cart' );
added before snippet make sure gets fired, works when logged out - not when logged in.
anyone got clue why?
ping @helgatheviking
an update, seems work if add following functions.php
add_action( 'wp_ajax_nopriv_woocommerce_add_variation_to_cart', 'so_27270880_add_variation_to_cart' ); add_action( 'wp_ajax_woocommerce_add_variation_to_cart', 'so_27270880_add_variation_to_cart' );
meaning, 1 logged in admins , 1 normal users. not sure why need both because every example have seen kind of extension/override mentions wp_ajax_nopriv_$function
hope helps have same problem me. , if explain me why needed, happy hear it.
Comments
Post a Comment