I’m currently trying to set up some filters for a custom post type within my admin. The custom post type is ‘players’ and I’m filtering them by another custom post type ‘teams’.
To create my dropdown list of teams I use get_posts to retrieve all my teams:
$args = array( 'numberposts' => -1, 'post_type'=> 'team', 'order' => 'ASC', 'orderby' => 'title' );
return get_posts( $args );
This works when I first arrive at the edit screen. Drop down list is rendered perfectly. I then perform the filter ( say by the Ladies 1st XI team ) and it works as expected, only players in the Ladies 1st XI are output. But my filter list isn’t working any more, and I’ve narrowed this down to get_posts not retrieving anything from my database.
I’ve done a few tests and no matter what I do get_posts stops working after I’ve performed the filter.
For note this is the code I use to output my team filter and perform the filter when required:
add_filter( 'parse_query', 'esf_admin_posts_filter' );
add_action( 'restrict_manage_posts','esf_restrict_listings_by_team' );
function esf_restrict_listings_by_team( ){
global $typenow;
if ( $typenow=='player' ) {
$teams = esf_get_teams();
?>
<select name="esf_team_select">
<option value=""><?php _e('Filter By Team', 'baapf'); ?></option>
<? foreach( $teams as $team): ?>
<option value="<?=$team->ID?>"><?=$team->post_title?></option>
<? endforeach; ?>
</select>
<?
}
}
function esf_admin_posts_filter( $query ){
global $pagenow;
if ( is_admin() && $pagenow=='edit.php' && isset( $_GET['esf_team_select']) && $_GET['esf_team_select'] != '') {
$query->query_vars['meta_key'] = 'esf_mm_teams';
$query->query_vars['meta_value'] = $_GET['esf_team_select'];
}
return $query;
}
Thanks in advance for any help you can offer!
Helen
That’s because
esf_admin_posts_filter()
will apply itself to your query insideesf_get_teams()
too!Adding
$query->is_main_query()
to theif
conditions inside your filter should prevent this.