Maxim Yakovlev
Maxim Yakovlev

Reputation: 31

Display the Min and Max prices in Woocommerce Product Category Archives

How Could I display the Min and the Max prices of the related products in the current Category.

Just 2 numbers - the price of the cheapest product category and the price of the most expensive product category.

Upvotes: 3

Views: 3892

Answers (2)

Ramgopal Lodhi
Ramgopal Lodhi

Reputation: 1

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

Upvotes: -1

LoicTheAztec
LoicTheAztec

Reputation: 254492

Here is an example of custom function hooked in single_term_title Wordpress specific filter hook, that will add the product price range to the category title.

It get from a SQL query all product prices for the current product category. Then it displays after the title the price range for the related products:

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;
}

Tested and works. You will get something like:

enter image description here

Upvotes: 2

Related Questions