Change AJAX Live Post Search Loop into foreach

Question

I was told that the reason for why the live post search does not work is because the loop needs changing into a foreach.

This is the code:

add_action( 'wp_ajax_data_fetch' , 'data_fetch' );
add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' );
function data_fetch() {

    global $wpdb;
    $post_search_query = $wpdb->get_results("SELECT * FROM wp_posts where post_type = 'post' and post_title like '%'".esc_attr( $_POST['search_keyword'] )."'%'");
    
    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-product-excerpt"><?php the_excerpt(); ?></span>

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

The search is dead. It shows nothing. Can someone please help me with this as I am at a loss. Here is the rest of the code:

add_shortcode('live_search', 'live_search_shortcode');
function live_search_shortcode(){

    $live_search = '<input type="text" class="live-search" 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
}
0
Sofia Herrmann 4 weeks 0 Answers 4 views 0

Leave an answer