Creating arguments from loop for WP_Query meta_query

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:

Read More
//$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

Related posts

1 comment

  1. 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,
        );
    }
    

Comments are closed.