正如我在上面的评论中所说,设置query_var => false
因为自定义分类法不是解决方案,因为这将使前端中的术语页返回404错误。放弃在前端使用术语页面,使其成为一个简单的工作表单,这远远不是一个解决方案。
我终于解决了这个问题。我没有将select元素中的名称设置为“my\\u tax[]”,而是将其设置为类似“tax\\u input[\'my\\u tax\']”[]。不要问我为什么Wordpress需要这个,但它解决了问题。
如果有人需要一个例子。
我的示例分类:
$taxonomies = array(
\'type\' => array(\'label\' => \'Types\',\'slug\' => \'type\',\'hierarchical\' => false,\'multiple\' => false),
\'city\' => array(\'label\' => \'Cities\',\'slug\' => \'city\',\'hierarchical\' => true,\'multiple\' => false),
\'community_features\' => array(\'label\' => \'Community features\',\'slug\' => \'community_features\',\'hierarchical\' => false,\'multiple\' => true),
\'property_features\' => array(\'label\' => \'Property features\',\'slug\' => \'property_features\',\'hierarchical\' => false,\'multiple\' => true)
);
foreach($taxonomies as $taxonomy => $properties){
register_taxonomy(
$taxonomy,
\'properties\',
array(
\'label\' => __( $properties[\'label\'] ),
\'hierarchical\' => $properties[\'hierarchical\'],
\'query_var\' => true,
)
);
register_taxonomy_for_object_type( $taxonomy, \'properties\' );
}
这里是一个示例表单:
<form method="post" action="<?php echo get_post_type_archive_link(\'properties\');?>">
<?php
foreach($taxonomies as $taxonomy) {
$args = array(
\'show_option_all\' => __(\'Select \'.$taxonomy[\'label\'],\'properties\'),
\'orderby\' => \'NAME\',
\'order\' => \'ASC\',
\'hide_empty\' => 0,
\'echo\' => 0,
\'selected\' => \'\',
\'hierarchical\' => true,
\'name\' => \'tax_input[\'.$taxonomy[\'slug\'].\'][]\',
\'class\' => \'\',
\'taxonomy\' => $taxonomy[\'slug\'],
);
if($taxonomy[\'multiple\']){
$args[\'show_option_all\'] = \'\';
}
$select = wp_dropdown_categories( $args );
if($taxonomy[\'multiple\']){
$select = preg_replace("#<select([^>]*)>#", "<select$1 multiple>", $select);
}
echo $select;
}
?>
<input type="hidden" name="action" id="action" value="search">
<button type="submit"><?php _e(\'Search\',\'properties\');?></button>
</form>
添加了自定义查询变量:
add_filter(\'query_vars\', \'properties_add_query_vars\');
function properties_add_query_vars( $vars) {
$vars[] = "action"; // name of the var as seen in the URL
return $vars;
}
我的示例pre\\u get\\u帖子:
add_action( \'pre_get_posts\', \'properties_pre_get_post\' );
function properties_pre_get_post($query){
if(isset($query->query_vars[\'action\']) && $query->query_vars[\'action\'] == \'search\'){
if($query->is_main_query() && !is_admin() && $query->is_archive ) {
$tax_query = array();
$tax_input = $_POST[\'tax_input\'];
if(!empty($tax_input)){
foreach($tax_input as $key => $value){
if(array_key_exists($key, $taxonomies)){
if(!empty($value) && $value[0] != "0"){
$value = array_map(\'intval\', $value);
$tax_query[] = array(
\'taxonomy\' => $key,
\'field\' => \'id\',
\'terms\' => $value,
\'operator\' => \'AND\'
);
}
}
}
$query->set(\'tax_query\',$tax_query);
}
}
}
}