【问题标题】:Change posts_per_page Into MySQL Query for WooCommerce AJAX Live Search将 posts_per_page 更改为 WooCommerce AJAX 实时搜索的 MySQL 查询
【发布时间】:2021-04-03 20:33:41
【问题描述】:

使用 posts_per_page 可能不是最佳选择,我想知道是否应该将其更改为 MySQL 查询以更快并减少对站点/服务器的压力?

这是为 WooCommerce 构建实时产品搜索的过程。

这是代码:

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();
}

我想知道是否有办法改变这一点:

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

进入 SQL 查询,如果是 - 如何?

【问题讨论】:

    标签: php mysql ajax search woocommerce


    【解决方案1】:

    你可以使用 wpdb。

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

    【讨论】:

    • 好的,很高兴知道 - 谢谢。有关如何从中获取所有产品的任何示例?
    • 你可以检查数据库表我认为 woo 上的产品在 wp_posts 表上,post_type = "product"
    • 或者通过使用这个 "SELECT * FROM wp_posts where post_type = 'product' and post_title like '%'.esc_attr( $_POST['search_keyword'] ).'%'"
    • 如果这个答案对您有帮助,欢迎您。如果您单击“接受此答案”,我将更加感激您的好日子^_^。
    • 我会尽快测试它。
    猜你喜欢
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2018-09-23
    • 2018-11-21
    • 2012-06-11
    • 2018-11-08
    • 2017-12-28
    相关资源
    最近更新 更多