显示Woocommerce产品类别档案中的最低和最高价格

时间:2017-12-11 18:35:26

标签: wordpress woocommerce categories product hook-woocommerce

如何显示当前类别中相关产品的最低和最高价格。

只需2个数字 - 最便宜的产品类别的价格和最昂贵的产品类别的价格。

2 个答案:

答案 0 :(得分:1)

以下是隐藏在 single_term_title Wordpress特定过滤器挂钩中的自定义功能示例,它会将产品价格范围添加到类别标题中。

它从SQL查询中获取当前产品类别的所有产品价格。然后它在标题后显示相关产品的价格范围:

add_filter( 'single_term_title', 'product_category_term_title', 10, 1 );
function product_category_term_title( $term_title ){
    // Only for product category archive pages
    if( ! (is_tax() && is_product_category() ) )
        return $term_title;

    // Get the current product category term object
    $term = get_queried_object();

    global $wpdb;

    # Get ALL related products prices related to a specific product category
    $results = $wpdb->get_col( "
        SELECT pm.meta_value
        FROM {$wpdb->prefix}term_relationships as tr
        INNER JOIN {$wpdb->prefix}term_taxonomy as tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
        INNER JOIN {$wpdb->prefix}terms as t ON tr.term_taxonomy_id = t.term_id
        INNER JOIN {$wpdb->prefix}postmeta as pm ON tr.object_id = pm.post_id
        WHERE tt.taxonomy LIKE 'product_cat'
        AND t.term_id = {$term->term_id}
        AND pm.meta_key = '_price'
    ");

    // Sorting prices numerically
    sort($results, SORT_NUMERIC);

    // Get the min and max prices
    $min = current($results);
    $max = end($results);

    // Format the price range after the title
    $price_range = sprintf( __( ' <small>(from %1$s to %2$s)</small>', 'woocommerce' ), wc_price( $min ), wc_price( $max ) );
    return $term_title . $price_range;
}

经过测试和工作。你会得到类似的东西:

enter image description here

答案 1 :(得分:0)

// remove blank price element from array.
$resultDirect = array_filter($results);
// min and max value from array
$min = min($resultDirect);
$max = max($resultDirect);