WordPress: implementare la ricerca AJAX per i prodotti di WooCommerce

WordPress: implementare la ricerca AJAX per i prodotti di WooCommerce

In WooCommerce è semplice creare una ricerca AJAX per i prodotti.

La soluzione è la seguente:


<?php
function my_wc_ajax_search() {
    $term = trim( esc_sql( $_GET['s'] ) );
    $args = array(
        'post_type' => 'product',
        's' => $term,
        'posts_per_page' => 12
    );
    $html = '';
    $loop = new WP_Query( $args );
    if( $loop->have_posts() ) {
        while( $loop->have_posts() ) {
            $loop->the_post();
            // Costruiamo la stringa HTML
        }
        wp_reset_postsdata();
    }
    echo $html;
    exit();
}

add_action( 'wp_ajax_my_wc_search', 'my_wc_ajax_search' );
add_action( 'wp_ajax_nopriv_my_wc_search', 'my_wc_ajax_search' );
?>

In jQuery avremo:


"use strict";
(function( $ ) {
    $(function() {
        $( "#searchform" ).on( "submit", function( e ) {
            e.preventDefault();
            var query = "action=my_wc_search&" + $( this ).serialize();
            var url = location.protocol + "//" + location.host + "/wp-admin/admin-ajax.php";
            $.get( url, query, function( html ) {
              if( html !== "" ) {
                 // Risultati
              } else {
                 // Nessun risultato
              }
            });
        });
    });
})( jQuery );

Torna su