Forked from Daniel217D/woocommerce - minimum and maximum price
Created
April 20, 2022 15:13
-
-
Save jswebschmiede/40c6a20ed4486091335e29d4ab64edec to your computer and use it in GitHub Desktop.
woocommerce - get minimum and maximum price for current products
This file contains 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
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