The following code, which I found in the forum, adds a category filtering function to the custom post list. This code can correctly filter the single-select taxonomy.
My custom post type, in actual use, the taxonomy is multi-select. When I choose a taxonomy with multiple selections, this code does not work for me.
For example: I have a post A, which belongs to both category ccat011 and category ccat012. When using the following code to filter, a null value is returned. If my post only belongs to the category ccat011, or only belongs to the category ccat012, it can be filtered normally.
Among them, my custom post type slug is: myp02
, and my custom taxonomy slug is: ccat01
I don't know how to modify the query method so that the code runs correctly. Any help is greatly appreciated.
/**
*
* Add classification filtering function for custom post list
* 为自定义帖子列表,添加分类筛选功能
*
**/
function filter_cars_by_taxonomiesmyp2( $post_type, $which ) {
// Apply this only on a specific post type
// 仅将其应用于特定帖子类型
if ( 'myp02' !== $post_type )
return;
// A list of taxonomy slugs to filter by
// 分类分类清单以进行过滤
$taxonomies = array( 'ccat01' );
foreach ( $taxonomies as $taxonomy_slug ) {
// Retrieve classified data 检索分类数据
$taxonomy_obj = get_taxonomy( $taxonomy_slug );
$taxonomy_name = $taxonomy_obj->labels->name;
// Search classification terms 检索分类术语
$terms = get_terms( $taxonomy_slug );
// Display filter HTML 显示过滤器HTML
echo "<select name='{$taxonomy_slug}' id='{$taxonomy_slug}' class='postform'>";
echo '<option value="">' . sprintf( esc_html__( '全部 %s', 'text_domain' ), $taxonomy_name ) . '</option>';
foreach ( $terms as $term ) {
printf(
'<option value="%1$s" %2$s>%3$s (%4$s)</option>',
$term->slug,
( ( isset( $_GET[$taxonomy_slug] ) && ( $_GET[$taxonomy_slug] == $term->slug ) ) ? ' selected="selected"' : '' ),
$term->name,
$term->count
);
}
echo '</select>';
}
}
add_action( 'restrict_manage_posts', 'filter_cars_by_taxonomiesmyp2' , 10, 2);