【问题标题】:Show lowest simple product price in category page在类别页面中显示最低的简单产品价格
【发布时间】:2017-05-04 06:50:26
【问题描述】:

我想在content-oroduct_cat.php 页面中显示最低的简单产品价格。来自Fancy Squares 的以下代码用于显示最低价格,但我只想显示简单产品,即省略分组产品。

/* SHOW LOWEST PRICE ON CATEGORY PAGE */
//woocommerce get lowest price in category
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));
}

我尝试使用:

AND {$wpdb->posts}.product_type = 'simple'

但这不起作用。我如何只显示简单的产品?

【问题讨论】:

    标签: php mysql wordpress woocommerce categories


    【解决方案1】:

    您的查询无效,因为product_type 未存储在 posts 表它存储在term_taxonomy 表中。要获得 希望您必须使用子查询,它将获取所有简单的 产品和主查询根据类别对其进行过滤。

    我已将您的wpq_get_min_price_per_product_cat() 修改如下

    function wh_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'
            AND {$wpdb->posts}.ID IN (SELECT posts.ID
                    FROM {$wpdb->posts} AS posts
                    INNER JOIN {$wpdb->term_relationships} AS term_relationships ON posts.ID = term_relationships.object_id
                    INNER JOIN {$wpdb->term_taxonomy} AS term_taxonomy ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
                    INNER JOIN {$wpdb->terms} AS terms ON term_taxonomy.term_id = terms.term_id
                    WHERE term_taxonomy.taxonomy = 'product_type'
                    AND terms.slug = 'simple'
                    AND posts.post_type = 'product')";
        return $wpdb->get_var($wpdb->prepare($sql, $term_id));
    }
    

    代码进入您的活动子主题(或主题)的functions.php 文件中。或者也可以在任何插件 php 文件中。

    用法

    echo wh_get_min_price_per_product_cat($cat_id);
    

    代码已经过测试并且可以工作。

    参考:SQL query to check product_type in WooCommerce

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 2016-08-22
      • 2019-08-28
      • 2021-12-17
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      相关资源
      最近更新 更多