Skip to content

Instantly share code, notes, and snippets.

@Daniel217D
Last active September 9, 2023 21:02
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Daniel217D/11c0ac0c2a70676448ff8007cb7cdce9 to your computer and use it in GitHub Desktop.
Save Daniel217D/11c0ac0c2a70676448ff8007cb7cdce9 to your computer and use it in GitHub Desktop.
woocommerce - get minimum and maximum price for current products
function get_filtered_price() {
global $wpdb;
$args = wc()->query->get_main_query();
$tax_query = isset( $args->tax_query->queries ) ? $args->tax_query->queries : array();
$meta_query = isset( $args->query_vars['meta_query'] ) ? $args->query_vars['meta_query'] : array();
foreach ( $meta_query + $tax_query as $key => $query ) {
if ( ! empty( $query['price_filter'] ) || ! empty( $query['rating_filter'] ) ) {
unset( $meta_query[ $key ] );
}
}
$meta_query = new \WP_Meta_Query( $meta_query );
$tax_query = new \WP_Tax_Query( $tax_query );
$meta_query_sql = $meta_query->get_sql( 'post', $wpdb->posts, 'ID' );
$tax_query_sql = $tax_query->get_sql( $wpdb->posts, 'ID' );
$sql = "SELECT min( FLOOR( price_meta.meta_value ) ) as min_price, max( CEILING( price_meta.meta_value ) ) as max_price FROM {$wpdb->posts} ";
$sql .= " LEFT JOIN {$wpdb->postmeta} as price_meta ON {$wpdb->posts}.ID = price_meta.post_id " . $tax_query_sql['join'] . $meta_query_sql['join'];
$sql .= " WHERE {$wpdb->posts}.post_type IN ('product')
AND {$wpdb->posts}.post_status = 'publish'
AND price_meta.meta_key IN ('_price')
AND price_meta.meta_value > '' ";
$sql .= $tax_query_sql['where'] . $meta_query_sql['where'];
$search = \WC_Query::get_main_search_query_sql();
if ( $search ) {
$sql .= ' AND ' . $search;
}
$prices = $wpdb->get_row( $sql ); // WPCS: unprepared SQL ok.
return [
'min' => floor( $prices->min_price ),
'max' => ceil( $prices->max_price )
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment