最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Filter admin columns by custom post field value

programmeradmin0浏览0评论

I have a custom post type called dogs. Within the Add Dog interface, I have a radio-button group that gives choices for color, which are added to the new dog post as meta data. There are about five color choices.

I also have the color field set up to be displayed as a sortable column in the admin area, when I look at all my dog posts. The sorting works as expected.

So now what I'd like to do is have each color value be a link which I can click, and when I click it, it filters all dog posts by that color value. So if I click "brown," I'll see a list of only brown dogs.

On Pages, we can click on an Author's name and see Pages filtered by that author. This is what I'd like, for color and the CPT dog.

I prefer to just do this in functions.php, and not use an enterprise plugin. Is there a way to do this?

I have a custom post type called dogs. Within the Add Dog interface, I have a radio-button group that gives choices for color, which are added to the new dog post as meta data. There are about five color choices.

I also have the color field set up to be displayed as a sortable column in the admin area, when I look at all my dog posts. The sorting works as expected.

So now what I'd like to do is have each color value be a link which I can click, and when I click it, it filters all dog posts by that color value. So if I click "brown," I'll see a list of only brown dogs.

On Pages, we can click on an Author's name and see Pages filtered by that author. This is what I'd like, for color and the CPT dog.

I prefer to just do this in functions.php, and not use an enterprise plugin. Is there a way to do this?

Share Improve this question edited Mar 20, 2019 at 19:52 Mark asked Mar 14, 2019 at 14:50 MarkMark 3211 gold badge3 silver badges16 bronze badges 5
  • 2 Would it be easy to change to use a custom taxonomy for colour instead? Then WP will just do all this for you. – Andy Macaulay-Brook Commented Mar 14, 2019 at 15:19
  • @AndyMacaulay-Brook Yes, I've considered the possibility for using a custom taxonomy, but I would have to migrate all the current meta data from its field to the new terms. I'm not sure if it would be worth the effort. Good point though. – Mark Commented Mar 14, 2019 at 20:07
  • I'm getting the sense that this is not possible if I keep 'color' as a custom meta field, as opposed to switching to a custom taxonomy. Would you all agree? – Mark Commented Mar 14, 2019 at 20:11
  • 1 It’s possible. Just a little complicated. You’ll see that when you add a taxonomy using register_taxonomy that you have a parameter to show the taxonomy in a column on edit.php and the terms are links that do exactly what you want. They use a query string for the parameter that is built-in to WP, ?Dog_color=blue, for example. For a custom field we need to write code to create a custom query argument and also to turn your column of fields into links using that argument. If I have time I’ll try and code you an answer tomorrow. – Andy Macaulay-Brook Commented Mar 14, 2019 at 20:13
  • I'm working out an answer, but could you post the section of code you've used to add the colours to the admin column? Then I can match my code for turning them into links. – Andy Macaulay-Brook Commented Mar 15, 2019 at 17:20
Add a comment  | 

3 Answers 3

Reset to default 5

For comparison, I made a post type of dog with both a custom field dog_colour and a taxonomy dog_colour.

With both added as admin columns, we get:

The taxonomy terms are automatically linked with a query variable, so clicking on one goes to a URL like http://example/wp-admin/edit.php?post_type=dog&dog_colour=red and only shows those dogs with the term red.

And for your data, a taxonomy would seem to be the right thing to use: all dogs have a colour and colour is something you might want to list dogs by.

But, there will be other use cases where a custom field is appropriate and where you might want to make the field clickable in the admin column to show all posts with that field value, so here goes...

Unlike taxonomies, custom fields don't automatically get a query var, so we add one like this:

function wpse331647_custom_query_vars_filter( $vars ) {
    $vars[] .= 'dogcolour';
    $vars[] .= 'dogbreed';
    return $vars;
}

add_filter( 'query_vars', 'wpse331647_custom_query_vars_filter' );

Now, calling a URL with ?dogcolour=red will set up a variable called dogcolour with the value red within the WP query.

We then need to modify the WP query to take account of this variable when it is present, but only in the admin and only when the query is for dogs:

add_action( 'pre_get_posts', 'wpse331647_alter_query' );

function wpse331647_alter_query( $query ) {

    if ( !is_admin() || 'dog' != $query->query['post_type'] )
        return;

    if ( $query->query_vars['dogcolour'] ) {
        $query->set( 'meta_key', 'dog_colour' );
        $query->set( 'meta_value', $query->query_vars['dogcolour'] );
    }

    if ( $query->query_vars['dogbreed'] ) {
        $query->set( 'meta_key', 'dog_breed' );
        $query->set( 'meta_value', $query->query_vars['dogbreed'] );
    }

}

And now, if we go to http://example/wp-admin/edit.php?post_type=dog&dogcolour=red we get:

The final step is for you to modify however you currently add the field to the admin column so that the field values are links with the correct value in the query string.

Where you currently have:

echo '<a href=http://localhost/wordpress/wp-admin/edit.php? dogcolour=' . $x . '>' . $x . '</a>';

try this instead:

echo '<a href="';
echo admin_url( 'edit.php?post_type=dog&dogcolour=' . urlencode( $x ) );
echo '">';
echo $x;
echo '</a>';

[only broken onto separate lines to help legibility]

PHP's urlencode() handles spaces in your meta values for you, and even URLs. WP's admin_url() will handle the correct domain, protocol/scheme and path to admin for you.

You could make your code more generic by using the post type query var rather than hard-coding it in, of course.

Based on @ Andy Macaulay-Brook comment on your question you can try this (it will add a dropdown next to the Filter button on top of the admin listing table):

add_action( 'restrict_manage_posts',  'filter_dogs_by_color' );

// Filter Dogs by Color
function filter_dogs_by_color( $post_type ) {
        if ( 'dog' !== $post_type ) return;    // Replace 'dog' with your post_type

        $taxonomy = 'color'; // Replace 'color' with your taxonomy slug

        $info_taxonomy = get_taxonomy($taxonomy);
        $selected      = isset($_GET[$info_taxonomy->query_var]) ? $_GET[$info_taxonomy->query_var] : '';

        wp_dropdown_categories(array(
             'show_option_all' => __("Show All {$info_taxonomy->label}"),
             'taxonomy'        => $taxonomy,
             'name'            => $info_taxonomy->query_var,
             'orderby'         => 'name',
             'selected'        => $selected,
             'hide_empty'      => true,
              'value_field'   => 'slug'
         )
        );
}

Take a look at Admin Columns Pro plugin, it gives you complete control over all columns and fields. Even images from custom fields work perfectly.

https://www.admincolumns/

They have a free version also:

https://wordpress/plugins/codepress-admin-columns/

发布评论

评论列表(0)

  1. 暂无评论