Pedro Pinto Pedro Pinto - 2 months ago 7
PHP Question

Custom WP_Query not working as intended

I'm trying to use a custom WP_Query but the results are not right.

I want to do is create a custom form to filter the Jobs registered with "WP Job Manager" using radius search.

This is my query:

$args = array(
'post_type' => 'job_listing',
'post_status' => array( 'publish' ),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'geolocation_long',
'value' => array($maxLong,$minLong),
'compare' => 'between',
'type' => 'numeric',
),
array(
'key' => 'geolocation_lat',
'value' => array($maxLat,$minLat),
'compare' => 'between',
'type' => 'numeric',
),
),
);

$the_query = new WP_Query( $args );


Can you spot any issue?

Any help would be appreciated. Thank you!

Answer

This may be a problem with the compare BETWEEN feature. I would suggest you have a look at the exact query being generated and whether the compare is actually comparing floats, not strings (which might produce unexpected results).

Have a look at the troubleshooting done for a very similar query over on wordpress.stackexchange.com.

The following is quoted from the question:

Since postmeta values are stored as strings, I figured I should be casting to DECIMAL, but it just seems to trim the decimal value from the string due to the lack of DECIMAL arguments/precision parameters.

and review Rarst's answer:

You can filter generated SQL and add precision parameters that you need.

Enable filters for get_posts() by adding following to query:

'suppress_filters' => false,

And:

add_filter('get_meta_sql','cast_decimal_precision');

function cast_decimal_precision( $array ) {

    $array['where'] = str_replace('DECIMAL','DECIMAL(10,3)',$array['where']);

    return $array;
}

Notice OP's comment on this suggestion too though:

tried both solutions and it looks like it compares them as strings with single quotes (wp 3.1.1), any ideas on that? trying raw sql did work though.

Please update your question with further findings to enable us to help you out.