Created
May 24, 2017 06:28
-
-
Save mohammadmursaleen/9e897aeb5e01874594b112e638e566e7 to your computer and use it in GitHub Desktop.
WordPress Plugin - Admin Post list table filter using post meta values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Admin Filter BY Custom Fields | |
Version: 1.0 | |
Author: Mohammad Mursaleen | |
*/ | |
add_action( 'restrict_manage_posts', 'obj_admin_posts_filter_restrict_manage_posts' ); | |
/** | |
* First create the dropdown | |
* make sure to change POST_TYPE to the name of your custom post type | |
* @author Mohammad Mursaleen | |
* @return void | |
*/ | |
function obj_admin_posts_filter_restrict_manage_posts(){ | |
$type = 'POST_TYPE'; | |
if (isset($_GET['post_type'])) { | |
$type = $_GET['post_type']; | |
} | |
//only add filter to post type you want | |
if ('POST_TYPE' == $type){ | |
//change this to the list of values you want to show | |
//in 'label' => 'value' format | |
$values = array( | |
'archive' => 'Archive', | |
'active' => 'Active', | |
'inactive' => 'Inactive', | |
); | |
?> | |
<select name="ADMIN_FILTER_FIELD_VALUE"> | |
<option value=""><?php _e('Filter By Status', 'Status'); ?></option> | |
<?php | |
$current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:''; | |
foreach ($values as $value=> $label ) { | |
printf | |
( | |
'<option value="%s"%s>%s</option>', | |
$value, | |
$value == $current_v? ' selected="selected"':'', | |
$label | |
); | |
} | |
?> | |
</select> | |
<?php | |
} | |
} | |
add_filter( 'parse_query', 'obj_posts_filter' ); | |
/** | |
* if submitted filter by post meta | |
* | |
* make sure to change status to the actual meta key | |
* and POST_TYPE to the name of your custom post type | |
* @author Mohammad Mursaleen | |
* @param (wp_query object) $query | |
* | |
* @return Void | |
*/ | |
function obj_posts_filter( $query ){ | |
global $pagenow; | |
$type = 'POST_TYPE'; | |
if (isset($_GET['post_type'])) { | |
$type = $_GET['post_type']; | |
} | |
if ( 'POST_TYPE' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '') { | |
$query->query_vars['meta_key'] = 'status'; | |
$query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE']; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment