I am performing a WP_Query on a custom post type called "task" that has a field "stage". I need to get all of the posts with a "stage" >= the "stage" of another task. Problem is stage is a string value, so using >= operator in the meta query won't work.
Currently my hack is to create an array that contains string value of numbers $stage to 50, and query for posts who's stage is in that array. This will work for the time being as no stage is above 12, but not a very scalable or dynamic solution. I'm wondering if there is a better way to mutate a value recieved in WP_query before the operator is used on it?
$stage = get_field('stage', $task_id);
$future_tasks = array();
for ($i = intval($stage); $i <= intval($stage) + 50; $i++) {
array_push($future_tasks, strval($i));
}
$tasks_query_args = array(
'post_type' => array('task'),
'posts_per_page' => -1,
'order' => 'DESC',
'meta_query' => array(
'0' => array(
'key' => 'project',
'value' => $project_id,
'compare' => '=',
),
'1' => array(
'key' => 'stage',
'value' => $future_tasks,
'compare' => 'IN',
),
'relation' => 'AND',
),
);
Ideally the second parameter of the query would be something like:
'1' => array(
'key' => 'stage',
'value' => intval($stage),
'compare' => '>=',
),
But that won't work because value of the stage field is a string.
Wondering if there are any ideas about how to better achieve this?
My Answer:
One way to achieve this is to use the `CAST` function in the `meta_query` to convert the string value of the `stage` field to a number before comparing it. Here's an example of how you can modify your `meta_query` to achieve this:
php
$tasks_query_args = array(
'post_type' => array('task'),
'posts_per_page' => -1,
'order' => 'DESC',
'meta_query' => array(
'0' => array(
'key' => 'project',
'value' => $project_id,
'compare' => '=',
),
'1' => array(
'key' => 'stage',
'value' => $stage,
'compare' => '>=',
'type' => 'NUMERIC',
),
'relation' => 'AND',
),
);
By adding the `'type' => 'NUMERIC'` parameter to the `meta_query`, you are telling WordPress to treat the value of the `stage` field as a number when comparing it. This way, you can compare the string values as numbers and get the desired results.
This should allow you to compare the `stage` field as numbers in your `WP_Query` without having to manually create an array of future stages.
Rate this post
3 of 5 based on 2008 votesComments