• Hello, hope someone can help with this issue I’m having filtering data with wp-query? Thanks…

    We have a custom made wp-query hooked up to a filter so we can filter a range of prices based between a pair of values set by another custom field. The prices are set up as integers using the ‘number’ field of Advanced Custom Fields.

    The issue is that the filter is comparing the price output as if it were a string, not a real number, therefore the results are inaccurate. I don’t know enough about the working of wp-query class to cast the returning data as an integer, if indeed this is the issue?

    // WP_Query base args
    	$args = array(
    		'post_type' => 'yacht',
    		'posts_per_page' => max(5,$_GET['size']),
    		'paged' => $paged,
    		// 'ignore_sticky_posts'=> 1,
    		// 'orderby' => 'title',
    		// 'order' => 'ASC',
    	);
    
    if($_GET['sort']) {
    		$args = array_merge( $args, array(
    			'orderby'  => 'meta_value_num',
    			'meta_key' => $sort_val
    		)); // default: price
    
    $metaQuery = array(); //array('relation' => 'AND');
    	//$taxQuery = array('relation' => 'AND');
    	$hasQuery = false;
    
    	// Add a filter using post meta fields to WP_Query
    	function addMetaQuery($value, $key, $type="CHAR", $compare="="){
    		global $metaQuery, $hasQuery;
    		$hasQuery = true;
    		$metaQuery[] = array(
    			'key' => $key,
    			'value' => $value,
    			'type' => $type,
    			'compare' => $compare
    		);
    	}
    
    	function addMetaQueryRange($value,$key){
    		// 3 types of query: range, bigger than, less than
    		$vals = explode('-',$value);
    		if($vals[0]&&$vals[1]) addMetaQuery($vals, $key, 'NUMERIC', 'BETWEEN');
    		elseif($vals[0]) addMetaQuery($vals[0], $key, 'NUMERIC', '>=');
    		elseif($vals[1]) addMetaQuery($vals[1], $key, 'NUMERIC', '<=');
    	}
    
    	// the main filters
    	if($_GET['type']) addMetaQuery($_GET['type'], 'type');
    	if(!$_GET['sale'] && $_GET['destination']) addMetaQuery(array($_GET['destination'],'both'), 'destination', 'CHAR', 'IN');
    	if($_GET['length']) addMetaQueryRange($_GET['length'],'length');
    	if($_GET['sale'] && $_GET['price']) addMetaQueryRange($_GET['price'],'price');
    	if($_GET['guests']) addMetaQuery($_GET['guests'], 'guests', 'NUMERIC', '>=');
    	if($_GET['year_built']) addMetaQueryRange($_GET['year_built'],'year');
    
    	if($hasQuery) $args['meta_query'] = $metaQuery;
    
    	$wp_query = new WP_Query($args);

    Many thanks,
    Andy

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Wp-query and ACF data type filter puzzle’ is closed to new replies.