WooCommerce: aggiungere un prodotto alla wish list con jQuery

WooCommerce: aggiungere un prodotto alla wish list con jQuery

In jQuery possiamo implementare una soluzione per l'aggiunta di un prodotto alla wish list di WooCommerce.

Definiamo il seguente codice nel template di WooCommerce single-product/meta.php:


<a class="wishlist-add" href="#" data-customer="<?php if( is_user_logged_in() ): echo get_current_user_id(); else: ?>0<?php endif; ?>" data-product="<?php echo get_the_ID(); ?>">
    <?php _e( 'Aggiungi alla wish list', 'textdomain' ); ?>
</a>

Creiamo la action AJAX nel file functions.php del nostro tema:


function my_add_to_wish_list() {
    $product_id = $_POST['product'];
    $user_id = (int) $_POST['customer'];
    $output = '';

    if( $user_id === 0 ) {
        $output = __( 'Effettua il login o registrati', 'textdomain' );
    } else {
        $list = get_user_meta( $user_id, 'wishlist', true );
        $data = array();
        if( empty( $list ) ) {
            update_user_meta( $user_id, 'wishlist', $product_id );
            
        } else {
            $items = explode( ',', $list );
            $in = array();
            if( in_array( $product_id, $items ) ) {
                
                $in[] = $product_id;
                foreach( $items as $item ) {
                    if( $item !== $product_id ) {
                        $in[] = $item;
                    }
                }
            } else {
                $in = $items;
                $in[] = $product_id;
            }

            update_user_meta( $user_id, 'wishlist', implode( ',', $in ) );
        }

        $output = __( 'Wish list aggiornata!', 'textdomain' );
    }
    echo $output;
    exit;
}

add_action( 'wp_ajax_my_wishlist', 'my_add_to_wish_list' );
add_action( 'wp_ajax_nopriv_my_wishlist', 'my_add_to_wish_list' );

Infine usiamo jQuery:


(function( $ ) {
    $(function() {
        if( $( ".wishlist-add" ).length ) {
            $( ".wishlist-add" ).click(function() {
                var $btn = $( this );
                $.post( "/wp-admin/admin-ajax.php", {
                    action: "my_wishlist", 
                    customer: $btn.data( "customer" ),
                    product: $btn.data( "product" )
                    }, function( message ) {
                        console.log( message );
                });
                return false;
            });
        }
    });
})( jQuery );

Torna su