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

How to exclude some post from admin edit screen

programmeradmin1浏览0评论

I want to restrict which post appears in a user edit screen based on its role. The roles are mapped to category.

  1. I am trying to add some conditions at the time posts are retrieved so that only posts belonging to a specific category are shown in the edit screen.

  2. I am not able to find out the appropriate hook to fire. I tried 'pre_get_posts' and then try to modify the query which satisfies the condition if (is_admin() && $query->is_main_query()) { but to no use.

I want to restrict which post appears in a user edit screen based on its role. The roles are mapped to category.

  1. I am trying to add some conditions at the time posts are retrieved so that only posts belonging to a specific category are shown in the edit screen.

  2. I am not able to find out the appropriate hook to fire. I tried 'pre_get_posts' and then try to modify the query which satisfies the condition if (is_admin() && $query->is_main_query()) { but to no use.

Share Improve this question asked Nov 25, 2020 at 1:15 Maanas RoyyMaanas Royy 101
Add a comment  | 

1 Answer 1

Reset to default 0

I'm not sure why you're having trouble with pre_get_posts as that is the correct hook to use. For example, if we wanted to restrict the edit.php screen to only show posts from authors when the current user is an author we could say:

/**
 * Pre Get Posts
 * Restrictions by Role
 * 
 * @return void
 */
function wpse378774_pgp( $query ) {
    
    // Return Early - Not Admin Panel
    if( ! is_admin() ) {
        return;
        
    // Return Early - Not Main Query
    } else if( ! $query->is_main_query() ) {
        return;
    }
    
    $user = wp_get_current_user();
    
    // Return Early - User not an author
    if( ! in_array( 'author', (array)$user->roles ) ) {
        return;
    }
    
    // Limit all queries to only show posts by author
    if( $query->is_main_query() ) {
        
        // Get all user IDs who are authors
        $user_query = new WP_User_Query( array(
            'role'      => 'author',
            'fields'    => 'ID',
        ) );
        $user_ids = $user_query->get_results();
        
        // Set our query modifier
        $query->set( 'author__in', $user_ids );
        
    }
    
}
add_action( 'pre_get_posts', 'wpse378774_pgp' );

For more information please review WP_Query and WP_User_Query.

发布评论

评论列表(0)

  1. 暂无评论