Filter by custom Field for Custom post type Admin Listing

I have a custom post type “Article” which has a custom field “issue” that is the id number of a “issue” post type that i am selecting using a simple select box.

I want to add a drop down of issues to filter the article listing found here:

edit.php?post_type=article

Is this possible? Is this sort of thing documented anywhere? I have not been able to find documentation or examples.

what hooks are there to filter lists & add selects to the filter controls?

2 Answers
2

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