//Load the search auto complete $('.searchinput').on("change keyup paste", function() { var value = $(this).val(); $('.search-field').val(value); if(value.length > 2) { autoComplete($(this).val()); } else { $('#search-section .ac-search-results').html(''); } }); $('.searchinput').on( "focusin", function() { setTimeout( function() { $('#search-section .ac-search-results').fadeIn(); }, 500); }); $('.searchinput').on( "focusout", function() { setTimeout( function() { $('#search-section .ac-search-results').fadeOut(); }, 500); });
ארכיון: Code Snippets
AutoComplete JS1
function autoComplete(s) { $.ajax({ url: MyAjax.ajaxurl, type: "GET", data: { 'action': 'get_search_autocomp', 's': s, }, dataType: "html", success: function (data) { $('#search-section .ac-search-results').html(data); }, error: function (errorThrown) { console.log(errorThrown); } }); }
AutoComplete HTML
<div class="ac-search-results"></div>
AutoComplete function
function get_search_autocomp() { if ( isset($_GET) ) { global $wp_query; $args = array( 'post_type' => 'product', 's' => $_GET['s'], 'posts_per_page' => 5 ); $loop = new WP_Query($args); ob_start(); if ($loop->have_posts()) : ?> <ul> <?php while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?> <li> <a href="<?= esc_url( home_url( '/?s=' ) ); ?><?= urlencode($product->get_name()); ?>"> <?= $product->get_name(); ?> </a> </li> <?php endwhile; ?> </ul> <?php endif; $output = ob_get_contents(); //Grab output ob_end_clean(); //Discard output buffer wp_reset_postdata(); echo $output; die; } wp_die(); } add_action( 'wp_ajax_'. $ajax_type . 'get_search_autocomp', 'get_search_autocomp' );