从循环为WP_QUERY META_QUERY创建参数

时间:2013-09-19 作者:SomeRandomDude

我正在尝试创建一个WP\\u查询,其结果参数如下:

$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\')
    )
);
我真正要做的是创建一个高级搜索,它可以让元值像这样搜索:

//$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*/

    )
);
我试图避免手动创建每个搜索参数:

          array(\'key\' => \'key1\', \'value\' => \'value1\'),
          array(\'key\' => \'key2\', \'value\' => \'value2\'),
          array(\'key\' => \'key3\', \'value\' => \'value3\')
只需使用$\\u SERVER[\'QUERY\\u STRING\']创建数组并循环,将数组添加到meta\\u QUERY

我很难将数组合并或添加到meta\\u查询

1 个回复
最合适的回答,由SO网友:Charles Clarkson 整理而成

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,
    );
}
结束

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post