Hide password protected posts in admin

You can use the has_password parameter of WP_Query.

Here’s an example how you can hide it, for non administrators, on the edit.php screen for the post post type:

/**
 * Hide password protected posts, for non-admins, in the case of 'edit-post' screen id
 *
 * @link http://wordpress.stackexchange.com/a/200426/26350
 */
add_action( 'pre_get_posts', function( \WP_Query $q )
{
    $screen = get_current_screen();

    if(    is_admin() 
        && ! current_user_can( 'manage_options' ) 
        && is_a( $screen, '\WP_Screen' ) 
        && 'edit-post' === $screen->id
    )
        $q->set( 'has_password', false );
} );

Hopefully you can adjust this to your needs.

PS: it would be handy to have a get_current_screen_id() function, similar to the get_current_user_id() function 😉

Update

/**
 * Hide password protected posts, for non-admins, in the case of 'edit-post' screen id. 
 * Here we don't restrict this to the current user.
 *
 * @link http://wordpress.stackexchange.com/a/200426/26350
 */
is_admin() && add_action( 'posts_where', function( $where, \WP_Query $q )
{
    $screen = get_current_screen();

    if(     
           ! current_user_can( 'manage_options' ) 
        && is_a( $screen, '\WP_Screen' ) 
        && 'edit-post' === $screen->id
    ){
        global $wpdb;
        $uid = get_current_user_id();
        $where .= $wpdb->prepare(
            " AND ( ( {$wpdb->posts}.post_password = '' AND {$wpdb->posts}.post_author != %d )
              OR ( {$wpdb->posts}.post_author = %d ) ) ",
            $uid,
            $uid
        );
    }
    return $where;
}, 10, 2 );

If WP_Query would support field_query:

It would be handy if WP_Query would support the field_query input argument, to make it easier to work with the post fields.

Here’s an example:

add_action( 'pre_get_posts', function( \WP_Query $q )
{
    $screen = get_current_screen();

    if(    is_admin() 
        && ! current_user_can( 'manage_options' ) 
        && is_a( $screen, '\WP_Screen' ) 
        && 'edit-post' === $screen->id
    )
        $q->set( 'field_query', 
            [
                'outer_relation' => 'AND',
                'relation'       => 'OR',
                [ 
                    'field'   => 'author',
                    'value'   => get_current_user_id(),
                    'compare' => '=',
                ],
                [
                    'relation'  => 'AND',
                    [
                        'field'     => 'author',
                        'value'     => get_current_user_id(),
                        'compare'   => '!=',
                    ],
                    [
                        'field'     => 'password',
                        'value'     => '',
                        'compare'   => '=',
                    ],
                ]       
            ]
        );
} );

I’ve a draft for such a plugin, so maybe I will post it here when it reaches the alpha stage 😉

Leave a Comment