How to IMPROVE Live AJAX based Search Form (Shortcode) for WordPress

Question

After much googling, reading and learning – I have finally finished my live ajax search form (shortcode) for WordPress.

As of now, I’ asking myself two things;

#1: is there a way to speed this up? perhaps a mysql query instead of "posts_per_page' => -1"?

#2: is there a way to search the content of each post and not just the title?

These two things is on my mind as I’m looking for ways to improve this.

Here’s is the full working code:

add_shortcode('live_search', 'live_search_shortcode' );
function live_search_shortcode() {
    
    $live_search = '<input type="text" name="postSearch" id="postSearch" placeholder="Type to Live Search"></input>
    <div id="datafetch"></div>';
    
    return $live_search;
}
    
add_action('wp_footer', 'jquery_live_search_data_fetch');
function jquery_live_search_data_fetch() { ?>

    <script type="text/javascript">

        (function($){

            var searchRequest = null;
            jQuery(function () {

        var minlength = 3;
        jQuery("#postSearch").keyup(function () {

            var that = this,
            value = jQuery(this).val();
            if (value.length >= minlength ) {
                if (searchRequest != null) 
                    searchRequest.abort();

                searchRequest = jQuery.ajax({

                    type: "POST",
                    url: "<?php echo admin_url('admin-ajax.php'); ?>",
                    data: {
                        action: 'data_fetch',
                        search_keyword : value
                    },
                    dataType: "html",
                    success: function(data){
                        if (value==jQuery(that).val()) {
                            jQuery('#datafetch').html(data);
                        }
                    }
                });
            }
                else {
            
            jQuery('#datafetch').html( '' );
        }
    });
});
}(jQuery));
</script>
<?php
}
    
add_action( 'wp_ajax_data_fetch' , 'data_fetch' );
add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' );
function data_fetch() {

    $post_search_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['search_keyword'] ), 'post_type' => 'post' ) );

    if( $post_search_query->have_posts() ) :
        
        while( $post_search_query->have_posts() ): $post_search_query->the_post(); ?>
            
            <h5><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h5>
            <span class="live-search-post-excerpt"><?php the_excerpt(); ?></span>

            <?php endwhile;
        wp_reset_postdata();
    endif;
    die();
}

Any ideas or thoughts?

0
Sofia Herrmann 5 months 2020-12-25T03:10:21-05:00 0 Answers 2 views 0

Leave an answer

Browse
Browse