Creating a AJAX based Live Post Search for Post Title (Shortcode)

Question

Based on the various answers from ajax live search for post title, I tried to modify the code and that way – create a custom version that only searches when a minimum of three characters are used and when empty, clear the search result.

Problem is, nothing happens when searching. The "search box" is there using [live_search], but nothing happens when typing into it.

This is my code so far, to which I’m gonna add in the post excerpt once I get it working:

add_shortcode( 'live_search', 'live_search_function' );
function live_search_function(){ ?>
<input type="text" name="postSearch" id="postSearch" onkeyup="fetch()"></input>
<div id="datafetch"></div>
<?php
}

add_action( 'admin_footer', 'fetch' );
function 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);
                            }
                        }
                    });
                }
            });
        });
    }(jQuery));
</script>
<?php
}

add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
    $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['search_keyword'] ), 'post_type' => 'post' ) );
    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post(); ?>
            <h3><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h3>
        <?php endwhile;
        wp_reset_postdata();  
    endif;
    die(); 
}
0
Sofia Herrmann 2 years 2020-12-24T07:11:01-05:00 0 Answers 3 views 0

Leave an answer

Browse
Browse