updated   : May 15, 2012
we now have 588 snippets
By : , on July 02, 2011 9:00 am

Add select menu to filter by custom field in admin

wordpress snippet

Adding this snippet to the functions.php of your wordpress theme will add a select menu with a list of all custom fields, just select the field you want to filter by and click the filter button.

( example screenshot )
snippet :  PHPcopy
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
}
source →
  • http://www.cliffpaulick.com Cliff Paulick

    Is there a way to create a front-end search, based on custom fields or custom taxonomies?

    • http://wpsnipp.com Kevin Chard

      Well this specific snippet is for the admin filtering, you could add the ability to have wordpress search custom fields as well. However with all that said I would check out the plugin search everything.  http://wordpress.org/extend/plugins/search-everything/

      • http://www.cliffpaulick.com Cliff Paulick

        Yes, I’ve seen that one and others. Just wondering if you had anything different/better – especially looking for a way to sync the search options.
        For example: If city = Tulsa, then narrow the state to only have 1 option = Oklahoma. Or if you choose Oklahoma first, then change the cities drop-down to only display cities in Oklahoma… Then press “Search”.

        Thanks again.

  • John K

    Kevin,

    thanks for the snippet. It works perfectly. I’m curious, does the ‘ba’ in ba_admin_posts_filter() stand for blog admin?

    • http://wpsnipp.com Kevin Chard

      The ba_admin_posts_filter function name is just a custom function it could be anything really. However in this case the author of the snippet included part of his domain name, en.bainternet.info as ba_

      • John K

        Kevin, here’s a snippet I wrote so the filter can have ‘%’ and ‘_’ wildcards, in case anyone wants such a thing:

        function ba_admin_where_filter($where){    if (strpos($where, ‘meta_value’) !== FALSE) { $where = preg_replace(‘/(.meta_value[^=]*)=(.*)$/U’, “$1 LIKE $2″, $where);  } return $where;}add_filter( ‘posts_where_request’, ‘ba_admin_where_filter’ );FYI, if you specify 0 as the filter, it returns all posts. This is true of your original code as well. I thought it was because$_GET['ADMIN_FILTER_FIELD_VALUE'] != ”

        evaluates to false, so I tried 
        strval($_GET['ADMIN_FILTER_FIELD_VALUE']) != ”

        but it still returned all posts. Oh well.

        • http://www.cliffpaulick.com Cliff Paulick

          Kevin, is there a way to show the hidden fields as well (i.e. the ones that start with underscore)? Thanks.

  • http://www.web-development-blog.com finalwebsites

    Nice snippet, thanks.
    I will change it to get it working for the pages section.

  • Tdale

    Just implemented your code and it works great for the stated purpose. With your code I am able to quickly see which posts do have an entry for a particular custom field, however, I am hoping there is a way to show which posts don’t have an entry for that same custom field so it will be easier for me to go back through an add the missing entry instead of having to open each post individually to see if it has data in that particular custom field.  Any thoughts hugely appreciated.  Thanks!

    • http://wpsnipp.com Kevin Chard

      Well the best way would be to add the custom field value to the admin post listing, you could modify this snippet to do something like that.

      http://wpsnipp.com/index.php/functions-php/add-featured-thumbnail-to-admin-post-columns/

      • Tdale

        I ended up finding a plugin called “Mass Custom Fields Manager” that allowed me to identify all my posts that didn’t have the custom field I wanted and automatically add in the field with a value of my choosing.  I was then able to successfully use your functionality to now filter for that new value.  Works fantastic.  That saved me from having to manually sort through almost 2,000 posts.  Thanks!!

        • http://wpsnipp.com Kevin Chard

          Cool glad to hear you got things running, 2000 post would certainly be a lot to update by hand. No problem glad I could help out!

  • http://www.facebook.com/people/Juan-Pérez/100000043114207 Juan Pérez

    hi kevin! nice snippet!
    but i’m having a problem with it… its not possible for me to filter the posts admin list by multiples filters.
    if i filter by my custom field and category, so… it brings me no results (indeed there are).

    what’s can be happening?

    • http://wpsnipp.com Kevin Chard

      I’m sure multiple values would be possible just not something I have looked into, Ill delve a little deeper and see about doing something like this in a future snippet.

  • http://www.knightnet.org.uk knightnet

    Excellent post, thanks Kevin. Implementing now on my sites!

    • http://wpsnipp.com Kevin Chard

      Cool glad to hear it.

  • Martino

    This is amazing.
    Is there a way to show the filter only on a custom post type edit page?

    I tried putting a 
    if (isset($_GET['post_type']) && $_GET['post_type'] == ‘product’)
    in the filter but it doesn’t seem to work.

  • Constantin

    Great post, thanks!