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