Change posts_per_page Into MySQL Query for WooCommerce AJAX Live Search

Viewed 63

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?

1 Answers

You can use wpdb.

global $wpdb;

$data = $wpdb->get_results("SELECT * FROM table");
Related