【问题标题】:wordpress custom query is too slowwordpress 自定义查询太慢了
【发布时间】:2018-07-12 14:25:15
【问题描述】:

我正在尝试使用 woocommerce 中的自定义表创建自定义过滤器。大约有 24 000 种产品使自定义过滤器非常慢。如何让它更快?

这是我的代码:

function custom_wpquery( $query ){
    if(isset($_GET['min-price'])){
    // the main query
    global $wp_the_query;
 global $wpdb;
    if ( 'product' === $query->get( 'post_type' ) ) {

        $rr = g($_GET['min-price'],$_GET['max-price']);

        foreach($rr as $rrr){

           $fabricc = $wpdb->get_results("SELECT * FROM CWF_posts WHERE post_title = '".$rrr."' AND post_type = 'product'");

           foreach($fabricc as $fabriccc){
        $cID[] = $fabriccc->ID;    
           }

        }

        //print_r();exit;
      //  foreach($cID as $cIDD){
          //  $cat= wp_get_post_terms( $dd->ID, 'product_cat' );
       // }
          //$dd = get_page_by_title( $rrr, OBJECT, 'product' );

         //   $include[]=$dd->ID;
           // 
           // $c[] = $cat[0]->slug;
            //$c2[] = $cat[1]->slug;
       $query->set('post__in', $cID); 
    }
    }
}
add_filter( 'pre_get_posts', 'custom_wpquery' );

谢谢

【问题讨论】:

  • 请不要通过字符串连接来创建查询。您对 SQL 注入攻击敞开心扉。为什么不只返回ids,而不是整行?你在post-title 上有一个索引,在post_type 上有一个索引吗?这些更改应该会阻止您扫描整个表并检索超出您需要的数据。
  • 感谢 Dragonthoughts

标签: php mysql wordpress woocommerce


【解决方案1】:

您可以在要查询的字段上创建多索引...由于您的一个字段是恒定的,我建议将您的 SQL 转换为

SELECT * FROM CWF_posts WHERE post_type = 'product' AND post_title = '".$rrr."'

并在 MySQL 上使用此命令在 post_typepost_title 上创建索引

CREATE INDEX type_title_index on CWF_posts (post_type, post_title)

你也可以检查

Understanding multiple column indexes in MySQL query

https://dev.mysql.com/doc/refman/8.0/en/create-index.html

【讨论】:

    猜你喜欢
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    相关资源
    最近更新 更多