Filter by custom Field for Custom post type Admin Listing

I had to modify max answer to get the filter working. Renaming the select to issue_restrict_articles stopped it incorrectly filtering & kept the filter controls on the screen. posts_where filter and a SQL query to actually filter.

function restrict_articles_by_issue() {
    global $wpdb;
    $issues = $wpdb->get_col("
        SELECT DISTINCT meta_value
        FROM ". $wpdb->postmeta ."
        WHERE meta_key = 'issue'
        ORDER BY meta_value
    ");
    ?>
    <label for="issue">Issues:</label>
    <select name="issue_restrict_articles" id="issue">
        <option value="">Show all</option>
        <?php foreach ($issues as $issue) { ?>
        <option value="<?php echo esc_attr( $issue ); ?>" <?php if(isset($_GET['issue_restrict_articles']) && !empty($_GET['issue_restrict_articles']) ) selected($_GET['issue_restrict_articles'], $issue); ?>>
        <?php
          $issue   = get_post($issue);
          echo $issue->post_title;
        ?>
        </option>
        <?php } ?>
    </select>
    <?php
}
add_action('restrict_manage_posts','restrict_articles_by_issue');



function posts_where( $where ) {
    if( is_admin() ) {
        global $wpdb;       
        if ( isset( $_GET['issue_restrict_articles'] ) && !empty( $_GET['issue_restrict_articles'] ) && intval( $_GET['issue_restrict_articles'] ) != 0 ) {
            $issue_number = intval( $_GET['issue_restrict_articles'] );

            $where .= " AND ID IN (SELECT post_id FROM " . $wpdb->postmeta ." 
WHERE meta_key='issue' AND meta_value=$issue_number )";
        }
    }   
    return $where;
}
add_filter( 'posts_where' , 'posts_where' );

Leave a Comment