• With pre_get_posts I extend the query with filters.
    I’m now trying to make a custom price filter, because i can’t use the original filter

    De code i’m using:

    $minprice = 0;
    $maxprice = 0;
    if ( isset( $_GET['min_price'] ) && $_GET['min_price'] > 0 ) $minprice = $_GET['min_price'];
    if ( isset( $_GET['max_price'] ) && $_GET['max_price'] > 0 ) $maxprice = $_GET['max_price'];
    
    if ( $minprice > 0 || $maxprice > 0 ) {
    	$compare = '=';
    	$metavalue = '';
    	if ( $minprice > 0 && $maxprice > 0 ) { $compare = 'between'; $metavalue = array( $minprice, $maxprice ); }
    	if ( $minprice > 0 && $maxprice <= 0 ) { $compare = '>='; $metavalue = $minprice; }
    	if ( $maxprice > 0 && $minprice <= 0 ) { $compare = '<='; $metavalue = $maxprice; }
    
    	$query->set( 'meta_key', 'price' );
    	$query->set( 'meta_value', $metavalue );
    	$query->set( 'meta_compare', $compare );
    }

    The problem is that if i fill in 10 for min_price i also get 2 euro products.
    I know WP is comparing the values as string.
    How can I make it numeric?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter famouswolluf

    (@famouswolluf)

    I made some progress by adding:
    $query->set( 'meta_type', 'decimal' );

    But when i fill in 10 as minprice and 20 as maxprice I also get results like 9,86 and 20,30.

    When i fill in 10.50 as minprice and 20 as maxprice, everything before 10,50 is gone as it shoot, but 20,30 is still there.

    Thread Starter famouswolluf

    (@famouswolluf)

    I have fonud the solution.
    It is an (old) mysql bug: https://bugs.mysql.com/bug.php?id=61691

    I have changed it to:
    $query->set( 'meta_type', 'DECIMAL(20,2)' );

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Filter products by price’ is closed to new replies.