获得Woocommerce中特定产品类别的大于0的简单“库存”产品的最低价格

时间:2019-04-07 16:40:09

标签: php mysql sql wordpress woocommerce

在WooCommerce中,对于定义的产品类别,当价格大于0时,我试图获取最低价格(可用的库存)。

我有这段显示最低价格的代码:

function wpq_get_min_price_per_product_cat($term_id){    
    global $wpdb;

    $sql = "
    SELECT  MIN( meta_value+0 ) as minprice
    FROM {$wpdb->posts} 
    INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)
    INNER JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id) 
    WHERE  
      ( {$wpdb->term_relationships}.term_taxonomy_id IN (%d) ) 
    AND {$wpdb->posts}.post_type = 'product'  
    AND {$wpdb->posts}.post_status = 'publish' 
    AND {$wpdb->postmeta}.meta_key = '_price'
    ";

    return $wpdb->get_var($wpdb->prepare($sql, $term_id));
}

但是如何定位价格大于0的“现货”产品?

1 个答案:

答案 0 :(得分:0)

对于已定义的产品类别术语ID,大于0的产品价格和“有货”的产品,以下更改的SQL查询将获得最低价格:

function wpq_get_min_price_per_product_cat( $term_id ){
    global $wpdb;

    return $wpdb->get_var( $wpdb->prepare("
        SELECT  MIN(pm.meta_value+0)
        FROM {$wpdb->prefix}posts as p
        INNER JOIN {$wpdb->prefix}postmeta as pm
            ON p.ID = pm.post_id
        INNER JOIN {$wpdb->prefix}postmeta as pm2
            ON p.ID = pm2.post_id
        INNER JOIN {$wpdb->prefix}term_relationships as tr
            ON p.ID = tr.object_id
        INNER JOIN {$wpdb->prefix}term_taxonomy as tt
            ON tr.term_taxonomy_id = tt.term_taxonomy_id
        WHERE tt.taxonomy = 'product_cat'
        AND tt.term_id = %d
        AND p.post_type = 'product'
        AND p.post_status = 'publish'
        AND pm.meta_key = '_price'
        AND pm.meta_value > 0
        AND pm2.meta_key = '_stock_status'
        AND pm2.meta_value = 'instock'
    ", $term_id) );
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。