0

I'm looking to query my posts via a custom field that I've created on my page. But the custom field is an array of values. So the custom field 'country' could look like this

country => usa,africa,united kingdom,poland

What's confusing me is how to query posts with a custom field which is an array seperated with ','?

I've tried quite a few solutions on here with no success.

Any suggestions would be greatly appreciated!

1 Answer 1

6

You can achive this using WP Query with meta_query argument as following.

$args = array (
    'post_type'              => array( 'post' ),  // YOUR POST TYPE
    'meta_query'             => array(
        array(
            'key'       => 'country',  
            'value'     => $your_country,  // THE COUNTRY TO SEARCH
            'compare'   => 'LIKE',  // TO SEARCH THIS COUNTRY IN YOUR COMMA SEPERATED STRING
            'type'      => 'CHAR',
        ),
    ),
);

// The Query
$query = new WP_Query( $args );

I have tested this query. Working perfect. Hope this might work for you as well.

Edit:

For multiple countries you can use following approach.

$countries_to_search = 'usa,africa,poland'; // YOUR COMMA SEPARATED STRING
$countries = explode( ',', $countries_to_search ); // CONVERT INTO ARRAY OF COUNTRIES
$meta_array = array();
$meta_array['relation'] = 'AND';  // DECLARE RELATION --> YOU CAN USE 'OR' AS WELL  

foreach($countries as $country){  // CREATE QUERY FOR EACH COUNTRY IN ARRAY

    $meta_array[] =  array(
        'key'       => 'country',  
        'value'     => $country,  // THE COUNTRY TO SEARCH
        'compare'   => 'LIKE',  // TO SEARCH THIS COUNTRY IN YOUR COMMA SEPERATED STRING
        'type'      => 'CHAR',
    );

}

$args = array (
        'post_type'     => array( 'post' ),  // YOUR POST TYPE
        'meta_query'    => $meta_array,  // ARRAY CONTAINING META QUERY
        );

// The Query
$query = new WP_Query( $args );
6
  • How would I query by multiple values? e.g. if I want a page to display all posts tagged with 'usa,africa,poland'?
    – Jonathan
    Commented Aug 2, 2015 at 14:08
  • @Jonathan I have edit my answer for multiple comma separated countries as well. Commented Aug 2, 2015 at 19:40
  • Would I be able to store the countries in a custom field within the page then call it? Instead of static values in your edit?
    – Jonathan
    Commented Aug 2, 2015 at 21:35
  • Sure that's just a variable. You can store any string you want and use it for search. It depends on your usage. Commented Aug 3, 2015 at 2:41
  • Thanks for the answers! How would I set the variable to a custom field within my page?
    – Jonathan
    Commented Aug 3, 2015 at 8:01

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.