Home / admin / Add select menu to filter by custom field in admin
  • How to Add select menu to filter by custom field in admin

    add-select-menu-to-filter-by-custom-field-in-admin

    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.

    ( example screenshot ) ( click code to copy )

    wordpress snippet : PHP

    <>
    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
    }
    

    ( WordPress codex functions, hooks, in this snippet. )

    query, query_vars, add_filter, add_action, selected, _n, _e, is_admin, wp,
  • Is there a way to create a front-end search, based on custom fields or custom taxonomies?

    • 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/

      • 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?

    • 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.

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

  • 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!

    • 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!!

        • 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!

  • 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?

    • 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.

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

  • 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!

  • joo-joo

    Hello, it seems really very interesting…

    But unfortunately it is not exactly I am looking for a long time.

    I really hate the search in Media Library. What is the purpose of search which is not able to find some attachment(s) neither by (sub)string in FILENAMEs, nor by ID, the strings in ALT or CAPTION, CUSTOM FIELDS, TAGS etc.. These standard SEARCH ability have every CMS but WP. Very strange. Do you have any idea hot to add something like this to Media Library “upload.php” and “media-upload.php” (pop-up window for inserting of attachments to Page/Post)?

    I am afraid I am not able to DIY, it is just above my knowledge of PHP. But it seems like you have the code ready for launch! In any case, this example is an inspiration for me.
    :-))

    • If you don’t add any information or keywords to your media records, how should you find them?
      Sure the WP search is very limited, but for the media it works fine if you add good ALT tags to every image 😉

      • joo-joo

        WHY to add it to meta data? Generally, FILENAME, ID, Author, etc. – all the information is present in database. Clever SQL can return the data. Not mentioning the problematic sort ASC/DESC columns – I mean the new columns added through function.php (FileSize, ID, etc.) I think the problem is apparent.

  • Balders

    Hi there,

    I just came across your custom field filter snippet.

    Is it possible to filter tags as well? Any idea what I need to change?

    Cheers

  • fausto

    Hi all, can anyone help me to create a custom function to sort post order without plugin ? I would like to include the ability to sort postorder like pages…

    I have some code like add_filter( ‘parse_query’, ‘my_custom_post_sort’ );

    but I do not know how to go on …

  • was looking for something like that. not so easy, and useful. thanks :)

  • Excellent. Post is somewhat elderly, yet I’ve just copied and pasted the code into my functions file and it works perfectly. (OK, not “perfectly” display wise, but tweaking is my problem! Functionally it seems spot on.) [WP 4.2.2] I’ve wanted this functionality for ages … and finding it was so easy once I decided to actually do something about that. Thanks EVERso! :-)