通过复选框表单进行WordPress查询

时间:2016-11-22 作者:onei0120

我有一个表格中的类别子类别列表,我希望用户选择他们想要包含在搜索结果中的所有子类别。一旦用户点击submit,他们将被带到另一个页面并显示结果。

<form>
     <?php
        $args = array(
            \'taxonomy\'      => \'category\',
            \'parent\'        => 0, // get top level categories
            \'orderby\'       => \'name\',
            \'order\'         => \'ASC\',
            \'hierarchical\'  => 1,
            \'pad_counts\'    => 0
        );

        $categories = get_categories( $args );

        foreach ( $categories as $category ){
            echo \'<div class="search-box">\';
                echo \'<div class="search-box-inside">\';
                    echo \'<h4>\'. $category->name . \'</h4>\';

                    $sub_args = array(
                        \'taxonomy\'      => \'category\',
                        \'parent\'        => $category->term_id, // get child categories
                        \'orderby\'       => \'name\',
                        \'order\'         => \'ASC\',
                        \'hierarchical\'  => 1,
                        \'pad_counts\'    => 0
                    );

                    $sub_categories = get_categories( $sub_args );

                    foreach ( $sub_categories as $sub_category ){

                        echo \'<label><input type="checkbox" id="type-\'. $sub_category->name . \'" rel="\'. $sub_category->name . \'">\'. $sub_category->name . \'</label>\';

                    }
                echo \'</div>\';
            echo \'</div>\';

        }
        ?>
            <input type="submit" value="Submit">
            </form>
到目前为止,我能够通过复选框回显子类别的列表,但如何将复选框值输入到可搜索的查询中,以便获得选定的所有子类别?

1 个回复
SO网友:brianjohnhanna

你的问题范围很广,但我想我能帮上忙。将名称设置为与要使用数组语法分组的名称相同([]). 将复选框的值设置为类别ID。

// ...
foreach ( $sub_categories as $sub_category ){    
    echo \'<label><input type="checkbox" id="type-\'. $sub_category->name . \'" rel="\'. $sub_category->name . \'" name="subcats[]" value="\' . $sub_category->term_id .\'">\'. $sub_category->name . \'</label>\';
}
// ...
那么,假设表单的方法是POST, 您将在表单的action 参数因此,在搜索结果页面上:

$subcategories = $_POST[\'subcats\'];

// You could then use the array of category ID\'s to do a WP_Query, for example:
$category_search_results = new WP_Query([
    \'category__in\' => $subcategories
]);