根据帖子元值筛选自定义帖子类型



我想在Wordpress Admin中使用post_meta的值创建一个自定义帖子类型的过滤器。我发现可以根据钩子'restrict_manage_posts'的分类法进行过滤,并且我设法使用以下代码实现此工作。我想修改它来过滤基于post_meta的值。我希望它是meta而不是分类法的原因是它不会在前端显示。它应该是一个过滤器,为用户的管理只。如何使用带有meta而不是分类法的过滤器?

add_action( 'restrict_manage_posts', 'add_admin_filters', 10, 1 );

public function add_admin_filters( $post_type ){
if( 'my_post_type' !== $post_type ){
return;
}
$taxonomies_slugs = array(
'my_taxonomy',
'my_other_taxonomy'
);
// loop through the taxonomy filters array
foreach( $taxonomies_slugs as $slug ){
$taxonomy = get_taxonomy( $slug );
$selected = '';
// if the current page is already filtered, get the selected term slug
$selected = isset( $_REQUEST[ $slug ] ) ? $_REQUEST[ $slug ] : '';
// render a dropdown for this taxonomy's terms
wp_dropdown_categories( array(
'show_option_all' =>  $taxonomy->labels->all_items,
'taxonomy'        =>  $slug,
'name'            =>  $slug,
'orderby'         =>  'name',
'value_field'     =>  'slug',
'selected'        =>  $selected,
'hierarchical'    =>  true,
) );
}
}

这个问题的解决方案是使用私有分类法而不是post_meta,然后可以创建过滤器。这样就不会在前端显示了。

/**
* Register a private 'Genre' taxonomy for post type 'book'.
*
* @see register_post_type() for registering post types.
*/
function wpdocs_register_private_taxonomy() {
$args = array(
'label'        => __( 'Genre', 'textdomain' ),
'public'       => false,
'rewrite'      => false,
'hierarchical' => true
);

register_taxonomy( 'genre', 'book', $args );
}
add_action( 'init', 'wpdocs_register_private_taxonomy', 0 );

最新更新