Search code examples
phpwordpresscomparison

Compare strings as numbers in WP_Query


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?


Solution

  • Seems like, using numeric type could solve the problem:

    $tasks_query_args = array(
        'post_type'      => array( 'task' ),
        'posts_per_page' => - 1,
        'order'          => 'DESC',
        'meta_query'     => array(
            '0'        => array(
                'key'     => 'project',
                'value'   => intval( $project_id ),
                'compare' => '=',
                'type'    => 'numeric',
            ),
            '1'        => array(
                'key'     => 'stage',
                'value'   => intval( $task_id ),
                'compare' => '>=',
                'type'    => 'numeric',
            ),
            'relation' => 'AND',
        ),
    );