Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save salmanbd96/d2968513006e8b9d9094 to your computer and use it in GitHub Desktop.
Save salmanbd96/d2968513006e8b9d9094 to your computer and use it in GitHub Desktop.
WordPress is full of some great features, although sometimes you need to add something extra
like the following snippet making WordPress just a little easier to use. This snippet will add a new
custom field select menu to your WordPress post, page listings. The menu will display a list of all custom
fields, just select the field you want to filter by. This snippet is only for the wp-admin however If you wanted to
do any sort of filtering on the front end of your site. View the following snippet that will let you filter by category
using search.
add_filter( 'parse_query', 'ba_admin_posts_filter' );
add_action( 'restrict_manage_posts', 'ba_admin_posts_filter_restrict_manage_posts' );
function ba_admin_posts_filter( $query )
{
global $pagenow;
if ( is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_NAME']) && $_GET['ADMIN_FILTER_FIELD_NAME'] != '') {
$query->query_vars['meta_key'] = $_GET['ADMIN_FILTER_FIELD_NAME'];
if (isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '')
$query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
}
}
function ba_admin_posts_filter_restrict_manage_posts()
{
global $wpdb;
$sql = 'SELECT DISTINCT meta_key FROM '.$wpdb->postmeta.' ORDER BY 1';
$fields = $wpdb->get_results($sql, ARRAY_N);
?>
<select name="ADMIN_FILTER_FIELD_NAME">
<option value=""><?php _e('Filter By Custom Fields', 'baapf'); ?></option>
<?php
$current = isset($_GET['ADMIN_FILTER_FIELD_NAME'])? $_GET['ADMIN_FILTER_FIELD_NAME']:'';
$current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
foreach ($fields as $field) {
if (substr($field[0],0,1) != "_"){
printf
(
'<option value="%s"%s>%s</option>',
$field[0],
$field[0] == $current? ' selected="selected"':'',
$field[0]
);
}
}
?>
</select> <?php _e('Value:', 'baapf'); ?><input type="TEXT" name="ADMIN_FILTER_FIELD_VALUE" value="<?php echo $current_v; ?>" />
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment