Skip to content

Instantly share code, notes, and snippets.

@yawalkar
Created October 25, 2016 08:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yawalkar/8b5cbd706c90f509279f45425ccc7dfc to your computer and use it in GitHub Desktop.
Save yawalkar/8b5cbd706c90f509279f45425ccc7dfc to your computer and use it in GitHub Desktop.
Fixes WooCommerce price filter widget max price issue
// Override the woocommerce default filter for getting max price for filter widget.
add_filter( 'woocommerce_price_filter_widget_max_amount', 'theme_woocommerce_price_filter_widget_max_amount', 10, 2 );
/**
* Fix max_price issue in price filter widget.
*
* @param int $max_price The price filter form max_price.
* @return int Max price for the filter.
*/
function theme_woocommerce_price_filter_widget_max_amount( $max_price ) {
$prices = theme_woocommerce_get_filtered_price();
$max_price = $prices->max_price;
return $max_price;
}
/**
* Gets and returns the min and max prices from database. WooCommerce filter function.
*
* @return object Min and Max prices from database.
*/
function theme_woocommerce_get_filtered_price() {
global $wpdb, $wp_the_query;
$args = $wp_the_query->query_vars;
$tax_query = isset( $args['tax_query'] ) ? $args['tax_query'] : array();
$meta_query = isset( $args['meta_query'] ) ? $args['meta_query'] : array();
if ( ! empty( $args['taxonomy'] ) && ! empty( $args['term'] ) ) {
$tax_query[] = array(
'taxonomy' => $args['taxonomy'],
'terms' => array( $args['term'] ),
'field' => 'slug',
);
}
foreach ( $meta_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 ('" . implode( "','", array_map( 'esc_sql', apply_filters( 'woocommerce_price_filter_post_type', array( 'product' ) ) ) ) . "')
AND {$wpdb->posts}.post_status = 'publish'
AND price_meta.meta_key IN ('" . implode( "','", array_map( 'esc_sql', apply_filters( 'woocommerce_price_filter_meta_keys', array( '_price' ) ) ) ) . "')
AND price_meta.meta_value > '' ";
$sql .= $tax_query_sql['where'] . $meta_query_sql['where'];
return $wpdb->get_row( $sql );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment