Posted by & filed under WordPress.

Been working on a project for the past couple of days, and spent a bit of time this morning trying to get WordPress to do something. As usual, WordPress came through. Just took me knowing what to enter.

What I’m working on is a plugin that adds to the <head> section of a page based on meta_key values in the posts. There are two potential keys, and if either one or both have content I need to act.

To start, I used the meta_query field in the query_posts function. Worked like a charm, but would only find if one of the two meta keys wasn’t blank. Dug a bit into meta.php and found what I was after.

$myPosts = query_posts(array(
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'field_1',
            'value' => '',
            'compare' => '!='
        ),
        array(
            'key' => 'field_2',
            'value' => '',
            'compare' => '!='
        )
    )
));

That was it. Just added relation=’OR’ to the argument array and now it finds all posts that have a value in either one of those meta keys.

Leave a Reply

Your email address will not be published. Required fields are marked *