Woocommerce查询返回产品,按total_sales排序

时间:2015-02-12 13:09:54

标签: mysql wordpress woocommerce

我检查过woocommerce报告,并且在查询中提取了尚未售出的产品?

以下是查询:

   SELECT  wp_terms.name as categoryname,v1.meta_value as thevalue, wp_terms.slug as categoryslug, wp_posts.post_title as mytitle, wp_terms.term_id as categoryid,wp_term_taxonomy.parent as categoryparent FROM wp_posts
    INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
    INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
    INNER JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id)
    INNER JOIN wp_postmeta v1 ON (wp_posts.ID = v1.post_id) AND v1.meta_key LIKE 'total_sales'
    WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'product' AND wp_terms.slug='garden-lighting' AND wp_posts.post_title NOT LIKE '%cable%' AND v1.meta_value !=0
    ORDER BY v1.meta_value DESC
LIMIT 8

我检查了返回的数组的结果,还没有售出的产品返回的是total_sales值吗?

我哪里出错了?我想要按特定类别退回产品并按总销售额订购。

1 个答案:

答案 0 :(得分:1)

为什么不使用WP_Query而不是尝试编写SQL语句?

如果我理解正确,以下内容应该返回“花园照明”中的前8个帖子。按销售排序,然后按标题排序。

$args = array( 
    'query_id' => 'exclude_cable',
    'post_type' => 'product',
    'post_status' => 'publish',
    'category_name' => 'garden-lighting',
    'posts_per_page' => 8,
    'orderby'  => array( 'meta_value_num' => 'DESC', 'title' => 'ASC' ),
    'meta_key' => 'total_sales'
);
$new_query = new WP_Query( $args );

编辑我添加了一些额外的参数。一个我忘了指定产品类型!哎呀。但另外,我添加了query_id参数。默认情况下,WordPress不对此做任何事情,但我们可以过滤posts_where子句并在那里使用它只修改此特定查询的posts_where

add_filter( 'posts_where' , 'so_28478323_posts_where', 10, 2 );

function so_28478323_posts_where( $where, $q ) {
    if ( 'exclude_cable' == $q->get( 'query_id', null ) ) {
        $where .= " AND wp_posts.post_title NOT LIKE '%cable%'";
    }
    return $where;
}