Just like in Adding a Taxonomy Filter to Admin List for a Custom Post Type? the filter parse_query
could be used, but here I’m using posts_where
.
The row All | Published | ...
is controlled by views_edit-{$post_type}
and the $views
array contains each item that’s a simple anchor tag.
First, we insert a couple of links – a separator and a Meta filter:
add_filter( 'views_edit-portfolio', 'meta_views_wpse_94630', 10, 1 );
function meta_views_wpse_94630( $views )
{
$views['separator'] = ' ';
$views['metakey'] = '<a href="https://wordpress.stackexchange.com/questions/94630/edit.php?meta_data=allorany&post_type=portfolio">Meta Key</a>';
return $views;
}
The link contains meta_data=allorany
(the custom field name), which will be used to filter by meta key.
And then, filter when needed:
add_action( 'load-edit.php', 'load_custom_filter_wpse_94630' );
function load_custom_filter_wpse_94630()
{
global $typenow;
// Adjust the Post Type
if( 'portfolio' != $typenow )
return;
add_filter( 'posts_where' , 'posts_where_wpse_94630' );
}
function posts_where_wpse_94630( $where )
{
global $wpdb;
if ( isset( $_GET[ 'meta_data' ] ) && !empty( $_GET[ 'meta_data' ] ) )
{
$meta = esc_sql( $_GET['meta_data'] );
$where .= " AND ID IN (SELECT post_id FROM $wpdb->postmeta WHERE meta_key='$meta' )";
}
return $where;
}