Add Custom Filter in Wordpress wp-admin
Copy Below Code
View As A Text File
Show Text Only
Show API
Edit Code
if (is_admin()){
//this hook will create a new filter on the admin area for the specified post type
add_action( 'restrict_manage_posts', function(){
global $wpdb, $table_prefix;
$post_type = (isset($_GET['post_type'])) ?? 'post';
//only add filter to post type you want
if ($post_type == 'product'){
//query database to get a list of years for the specific post type:
$values = array();
$query_years = $wpdb->get_results("SELECT year(post_date) as year from ".$table_prefix."posts
where post_type='".$post_type."'
group by year(post_date)
order by post_date");
foreach ($query_years as &$data){
$values[$data->year] = $data->year;
}
//give a unique name in the select field
?><select name="vendor_id">
<option value="">All Vendor</option>
<?php
$args = array(
'role' => 'Vendor',
);
$users = get_users( $args );
$slectedVendorID = $_GET['vendor_id'] ?? '0';
foreach ( $users as $user ) {
?>
<option value="<?php echo $user->id; ?>" <?php if($slectedVendorID==$user->id){ ?>selected<?php } ?>><?php echo $user->display_name; ?></option>
<?php
}
?></select><?php
}
});
//this hook will alter the main query according to the user's selection of the custom filter we created above:
add_filter( 'parse_query', function($query){
global $pagenow;
// echo '<pre>';print_r($query);echo '</pre>';exit;
$post_type = (isset($_GET['post_type'])) ?? 'post';
if ($post_type == 'product' && $pagenow=='edit.php' && isset($_GET['vendor_id']) && !empty($_GET['vendor_id']))
{
// $query->query_vars['vendor_id'] = 6;
// echo '<pre>';print_r(get_query_var(''));echo '</pre>';exit;
$query->query_vars['meta_key'] = 'vendor_id';
$query->query_vars['meta_value'] = $_GET['vendor_id'];
}
});
}