0

I have a custom post type, "Jobs".

These jobs have an ACF checkbox field, "city". "Jobs" can have more than one "city," so the jobs returned have meta values look something like this:

[city] => Array
    (
        [0] => Austin
    ) 


[city] => Array
    (
        [0] => [Austin]
        [1] => [Boulder]
    )

[city] => Array
    (
        [0] => [Seattle]
        [1] => [Portland]
        [2] => [Boulder]
    )

I need to write a get_posts query so that I can return only jobs that match a single city.

However, I can't figure out what my arguments need to look like, since I need to match the value of "meta_value" is an array.

Here's my code, can you guys help?

function get_city_jobs() {
    $args = array( 
        'post_type'     =>  'careers_post_type', 
        'numberposts'   =>  -1,
        'meta_key'      =>  'city',
        'meta_value'    =>  'Boulder',
        'meta_compare'  =>  'LIKE'
    );

    $jobs = get_posts($args);

    foreach ($jobs as $job) {
        echo "<pre>";
        print_r( get_fields($job->ID));
        echo "</pre>";
    }

}

1 Answer 1

1

OK, I found the answer here:

WP Query post meta value

Turns out you have to use the serialize php function due to how wordpress stores arrays in the database.

function get_city_jobs() {

    $city = ($_GET['city']);
    $city = trim(ucfirst($city));

    $args = array( 
        'post_type'     =>  'careers_post_type', 
        'numberposts'   =>  -1,
        'meta_query' => array(
            array(
                'key' => 'city',
                'value' => serialize($city),
                'compare' => 'LIKE'
            )
        )
    );

    return get_posts($args);

}
2
  • Does this also work if a job has multiple cities?
    – kero
    Sep 27, 2018 at 18:21
  • 1
    @kero yes it does -- it pulls jobs regardless the size of the cities[] array.
    – qotsa42
    Sep 27, 2018 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.