Skip to content

Instantly share code, notes, and snippets.

@devinsays
Created September 25, 2021 21:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devinsays/f411ebd59d0436673a6ecf6630fa94d4 to your computer and use it in GitHub Desktop.
Save devinsays/f411ebd59d0436673a6ecf6630fa94d4 to your computer and use it in GitHub Desktop.
Categories with price range
$cat_args = array(
'orderby' => 'name',
'order' => 'asc',
'hide_empty' => false,
);
$product_categories = get_terms( 'product_cat', $cat_args );
foreach ( $product_categories as $key => $category ) {
$range = reddit_get_category_price_range( $category->term_id );
echo $category->name . " " . $range;
}
/**
* Returns the min and max price for a given product category.
*
* @param int $number
*
* @return string
*/
function reddit_get_category_price_range( $product_cat_id ) {
$products = get_posts([
'post_type' => 'product',
'posts_per_page' => -1,
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => $product_cat_id,
'operator' => 'IN'
),
array(
'taxonomy' => 'product_visibility',
'field' => 'slug',
'terms' => 'exclude-from-catalog', // Possibly 'exclude-from-search' too
'operator' => 'NOT IN'
)
)
]);
if ( ! $products ) {
return "";
}
$prices = array();
foreach ( $products as $product_id) {
$product = wc_get_product( $product_id );
$prices[] = $product->get_price();
}
if ( $prices ) {
$min = min( $prices );
$max = max( $prices );
return "$min - $max";
}
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment