Created
September 25, 2021 21:06
-
-
Save devinsays/f411ebd59d0436673a6ecf6630fa94d4 to your computer and use it in GitHub Desktop.
Categories with price range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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