I’m trying to filter my post in my admin area with a custom filter dropdown.
I use this method to make it:
https://wordpress.stackexchange.com/a/45447/84541
Here is my code:
add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts' );
function wpse45436_admin_posts_filter_restrict_manage_posts(){
$type="post";
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
//only add filter to post type you want
if ('post' == $type){
//change this to the list of values you want to show
//in 'label' => 'value' format
$values = array();
$testting = get_posts(array('posts_per_page'=>-1, 'post_type'=>'edition'));
foreach($testting as $post):
$values[$post->post_title] = $post->ID;
endforeach;
?>
<select name="ADMIN_FILTER_FIELD_VALUE">
<option value=""><?php _e('Toutes les éditions ', 'wose45436'); ?></option>
<?php
$current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
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', 'wpse45436_posts_filter' );
function wpse45436_posts_filter( $query ){
global $pagenow;
$type="post";
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
if ( 'post' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '') {
$query->query_vars['meta_key'] = 'n_de_ldition';
$query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
}
}
When I click on filter after selecting my option in my dropdown select, It does filter fine but my query who was adding option in my select is empty. I can’t understand what I’m doing wrong, is this because I use a get_posts to get my custom post type informations?
Here are some image.
When not filtered but clicked on select dropdown:
After filtering, options from selected dropdown are no more avaible but filters has worked fine:
If I replace this:
$values = array();
$testting = get_posts(array('posts_per_page'=>-1, 'post_type'=>'edition'));
foreach($testting as $post):
$values["N°".$post->post_title] = $post->ID;
endforeach;
whit this:
$values = array(
'label' => 'value',
'label1' => 'value1',
'label2' => 'value2',
);
It works fine but I have to change my labels and my values dynamicly.
Any Idea?
Thank’s in advance.