How to add new tab to admin list of posts and handle result list

Admin links

The goal is to show posts with special values of custom field (post meta) in separate tab.
I know how to add new tab, here is a code:

add_action( 'views_edit-post', 'remove_edit_post_views' );
function remove_edit_post_views( $views ) {
        $views['pre'] = '<a class="'.$class.'" href="'.admin_url().'edit.php?yourlink">Name of Sort</a>';
        return $views;
}

but I have no idea how and where I can filter posts.

Any ideas?

1 Answer
1

Admin post queries can be filtered just like frontend queries using pre_get_posts and checking for is_admin.

add_action( 'views_edit-post', 'remove_edit_post_views' );
function remove_edit_post_views( $views ) {
    $views['pre'] = '<a href="'.admin_url().'edit.php?pre=pre">My Special Posts</a>';
    return $views;
}

add_action('pre_get_posts', 'my_special_list');

function my_special_list( $q ) {
  $scr = get_current_screen();
  if ( is_admin() && ( $scr->base === 'edit' ) && $q->is_main_query() ) {
    // To target only a post type uncomment following line and adjust post type name
    // if ( $scr->post_type !== 'post' ) return;
    // if you change the link in function above adjust next line accordingly
    $pre = filter_input(INPUT_GET, 'pre', FILTER_SANITIZE_STRING);
    if ( $pre === 'pre' ) {
      // adjust meta query to fit your needs
      $meta_query = array( 'key' => 'is_special', 'value' => 'yes', );
      $q->set( 'meta_query', array($meta_query) );
    }
  }
}

Leave a Comment