WordPress多分类查询

时间:2016-11-03 作者:Kevin Nugent

我有一个简单的表单,由两个多重选择组成,它(就像魔术一样)用URL参数过滤我的帖子存档:

<form class="filters">
    <select name="country" multiple>
        <option value="united-kingdom">United Kingdom</option>
        <option value="ireland">Ireland</option>
    </select>
    <select name="type" multiple>
        <option value="director">Director</option>
        <option value="partner">Partner</option>
    </select>
    <input type="submit">
</form>
如果我选择“爱尔兰”和“合作伙伴”,我将被发送到:

https://example.com/network/?country=ireland&_type=partner
然后,如果我选择多个值,如“爱尔兰”、“英国”和“合作伙伴”,我将被发送到:

https://example.com/network/?country=ireland&country=united-kingdom&_type=partner
我的问题是,我如何使用此表单创建更像https://example.com/network/?country=ireland,united-kingdom&type=partner?

1 个回复
SO网友:jgraup

也许您可以在HTML中添加一个隐藏字段,该字段将通过\'relation\' => \'OR\'.

<input type="hidden" name="tax_query[relation]" value="OR">

<select name="tax_query[][country]" multiple>
    <option value="united-kingdom">United Kingdom</option>
    <option value="ireland">Ireland</option>
</select>

<select name="tax_query[][type]" multiple>
    <option value="director">Director</option>
    <option value="partner">Partner</option>
</select>
这意味着:

tax_query[relation]=OR&tax_query[][country]=united-kingdom&tax_query[][type]=director

Array
(
    [tax_query] => Array
        (
            [relation] => OR
            [0] => Array
                (
                    [country] => united-kingdom
                )

            [1] => Array
                (
                    [type] => director
                )

        )

)
似乎是你的network 页面是自定义的,可以通过$_REQUEST.

仅参考如何处理多个taxonomy queries 和建模基于http_build_query() 添加\'relation\' => \'OR\'.

$args = http_build_query( array (

    \'post_type\' => \'post\',

    \'tax_query\' => array (

        \'relation\' => \'OR\',

        array (
            \'taxonomy\' => \'movie_genre\',
            \'field\'    => \'slug\',
            \'terms\'    => array ( \'action\', \'comedy\' ),
        ),

        array (
            \'taxonomy\' => \'actor\',
            \'field\'    => \'term_id\',
            \'terms\'    => array ( 103, 115, 206 ),
            \'operator\' => \'NOT IN\',
        ),
    ),
) );

echo "<pre>";

echo PHP_EOL . $args . PHP_EOL;

print_r( wp_parse_args( $args ) );
最终看起来像:

post_type=post&tax_query%5Brelation%5D=AND&tax_query%5B0%5D%5Btaxonomy%5D=movie_genre&tax_query%5B0%5D%5Bfield%5D=slug&tax_query%5B0%5D%5Bterms%5D%5B0%5D=action&tax_query%5B0%5D%5Bterms%5D%5B1%5D=comedy&tax_query%5B1%5D%5Btaxonomy%5D=actor&tax_query%5B1%5D%5Bfield%5D=term_id&tax_query%5B1%5D%5Bterms%5D%5B0%5D=103&tax_query%5B1%5D%5Bterms%5D%5B1%5D=115&tax_query%5B1%5D%5Bterms%5D%5B2%5D=206&tax_query%5B1%5D%5Boperator%5D=NOT+IN

并且可以通过wp_parse_args().