简体   繁体   中英

Filter custom post type based on post meta value

I want to create a filter in Wordpress Admin for a custom post type using the value of post_meta. I found that it's possible to filter based on a taxonomy from the hook 'restrict_manage_posts' , and I managed to get this working using the following code. I'd like to modify it to filter based on the value of the post_meta. The reason I want this to be meta instead of taxonomy is so that it doesn't show on the front end. It should be a filter for the user's admin only. How can I use the filter with meta instead of taxonomy?

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,
        ) );
    }
}

The solution to this is to use a private taxonomy instead of post_meta, and then you can create the filter. That way it doesn't show on the front end.

 /**
 * 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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM