1

I'm trying to create a WP_Query with the outcome arguments such as:

$args = array(
    'post_type' => array( 'post', 'custom' ),
    'meta_query' => array(
       'relation' => 'AND',
          array('key' => 'key1', 'value' => 'value1'),
          array('key' => 'key2', 'value' => 'value2'),
          array('key' => 'key3', 'value' => 'value3')
    )
);

What I'm really doing is creating an advanced search which gets the meta values to search like this:

//$queryData = array();
//parse_str($_SERVER['QUERY_STRING'], $queryData);  

$queryData = array('key1' => 'value1','key2' => 'value2','key3' => 'value3');

$args = array(
    'post_type' => array( 'post', 'custom' ),
    'meta_query' => array(
       'relation' => 'AND',

       /* ADD $queryData loop HERE*/

    )
);

I'm trying to avoid to manually create each search parameter:

          array('key' => 'key1', 'value' => 'value1'),
          array('key' => 'key2', 'value' => 'value2'),
          array('key' => 'key3', 'value' => 'value3')

and just use $_SERVER['QUERY_STRING'] to create array and loop to add the arrays to meta_query

I'm having difficulty merging or adding the arrays to meta_query

1
  • 1
    Please include the code that does actual merging. Also so far this seems to be array manipulation in the realm of generic PHP and likely better asked at Stack Overflow.
    – Rarst
    Commented Sep 19, 2013 at 12:38

1 Answer 1

3

How about this?

/**
 * Convert query string to meta query.
 */
function query_string_to_meta_query( $query_string ) {
    $meta_query = array( 'relation' => 'AND' );

    foreach ( wp_parse_args( $query_string ) as $key => $value ) {
        $meta_query[] = array( 'key' => $key, 'value' => $value );
    }

    return array(
        'post_type'  => array( 'post', 'custom' ),
        'meta_query' => $meta_query,
    );
}
0

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.