X

Cómo filtrar tus entradas y páginas por campo personalizado en el panel de WordPress

Snippets by IsItWP

¿Quieres filtrar tus entradas por campo personalizado en el administrador de WordPress? Este fragmento añadirá un nuevo menú desplegable de campos personalizados a los listados de entradas y páginas de WordPress. El menú mostrará una lista de todos los campos personalizados. Para filtrar las entradas y páginas, sólo tiene que seleccionar el campo por el que desea filtrar.

add select menu to filter by custom field admin

Instrucciones:

Todo lo que tienes que hacer es añadir este código al archivo functions.php de tu tema o en un plugin específico del sitio:

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
}

Nota: Si es la primera vez que añade fragmentos de código en WordPress, consulte nuestra guía sobre cómo copiar / pegar correctamente fragmentos de código en WordPress, para no romper accidentalmente su sitio.

Si te ha gustado este fragmento de código, por favor considere revisar nuestros otros artículos en el sitio como: 62 mejores temas gratuitos para blogs de WordPress o 7 mejores plugins para formularios de contacto de WordPress.

Comentarios   Deja una respuesta

  1. Hi, is it possible to only view this on a certain type of post? Thank you

  2. Hi, thanks for the code, but unfortunately it doesn’t work for me. The selection dropdown appears above post list and has the right custom fields but if I write a value – it won’t display any results even though there is a number of posts that have this value in this custom field.

  3. hi i want to use his for Users custom post, how will the code change can anyone help me out!!

  4. Still working smoothly. Thanks, great snippet!

  5. 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! 🙂

  6. Salvatore Capolupo enero 3, 2015 en 4:13 pm

    was looking for something like that. not so easy, and useful. thanks 🙂

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

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

  9. 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.
    :-))

    1. 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 😉

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

  10. Great post, thanks!

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

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

    1. Cool glad to hear it.

  13. 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?

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

  14. 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!

    1. 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/

      1. 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!!

        1. 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!

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

    1. Glad to hear you like the snippet if you make any changes sending the changes back to wpsnipp.com via our contribute form http://wpsnipp.com/index.php/contribute/ would be great for our visitors. Enjoy the snippet!

    2. Hi Finalwebsites, have you changed the code? Can you help me?

        1. Thanks for posting the snippet update,

        2. Thank You! But the link gives me timeout!

  16. Kevin,

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

    1. 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_

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

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

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

    1. 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/

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

        1. Nothing that I have posted so far, however you can add category selection to search. I use that option in the search box on wpsnipp.com, could setup cities as categories.

          http://wpsnipp.com/index.php/cat/search-category-with-dropdown/

Añadir un comentario

Nos alegra que haya decidido dejar un comentario. Tenga en cuenta que todos los comentarios se moderan de acuerdo con nuestra política de privacidad , y que todos los enlaces son nofollow. NO utilice palabras clave en el campo del nombre. Tengamos una conversación personal y significativa.

WordPress Launch Checklist

La lista definitiva para lanzar WordPress

Hemos recopilado todos los elementos esenciales de la lista de comprobación para el lanzamiento de su próximo sitio web de WordPress en un práctico ebook.
Sí, envíeme el ¡gratuito!