0

I'm adding a filter on my custom post type 'book' list page for easier searching. I've found the relevant code and everything is good except that the filter not only appeared on the 'book' list page, but also on other list pages, for example, the post list page. I've reviewed the code but am still clueless.

<?php
add_action( 'restrict_manage_posts', 'book_genre_filter_page' );

function book_genre_filter_page(){
$type = 'book';

if ('book' == $type){

    $values = array(
        'Science Fiction' => 'sf', 
        'Autobiography' => 'ab',
        'Thriller' => 't',
    );
    ?>
    <select name="genre">
    <option value=""><?php _e('All genres', 'book_genre'); ?></option>
    <?php
        $current_v = isset($_GET['genre'])? $_GET['genre']:'';
        foreach ($values as $label => $value) {
            printf
                (
                    '<option value="%s"%s>%s</option>',
                    $value,
                    $value == $current_v? ' selected="selected"':'',
                    $label
                );
            }
    ?>
    </select>
    <?php
}
}


add_filter( 'parse_query', 'book_genre_filter' );

function book_genre_filter( $query ){
global $pagenow;
$type = $query->query['post_type'];
    $target = 'book';

    if ( $type == $target ) {
        if ( $pagenow =='edit.php' && isset($_GET['genre']) && $_GET['genre'] != '') {
                $query->query_vars['meta_key'] = 'genre';
                $query->query_vars['meta_value'] = $_GET['genre']; 
        }
    }
}
1

The restrict_manage_posts hook supplies the current post type as the very first parameter to the callback function (which is book_genre_filter_page() in your code), so you should use it (instead of the static $type variable in your code) to determine the current post type or to ensure your custom filter is displayed only on the admin screen for editing posts in your post type:

add_action( 'restrict_manage_posts', 'book_genre_filter_page' );
function book_genre_filter_page( $post_type ) {
    if ( 'book' == $post_type ) {
        ... your code here ...
    }
}
  • 1
    Thank you very much~ – Gary Hu Oct 17 at 1:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.