Using posts_per_page might not be the best option and I'm wondering if it should be changed into a MySQL query to be quicker and add less stress to site / server?
This is a process for building a live product search for WooCommerce.
This is the code:
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' => 'product' ) );
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();
}
Whereof I'm wondering if there's a way to change this:
$post_search_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['search_keyword'] ), 'post_type' => 'product' ) );
into an SQL query and if so - how?