1

I would like to restrict access for logged in users to specific posts: their own posts and my posts (as they will serve as templates for them).

I find this code snippet that works perfectly to show them their own posts, but I would like them to be able to see my posts as well. Do you have any idea how I can do that? how I can update this code to make it work as I wish?

Many thanks in advance for your help. That will be much appreciated... ;-)


add_action('pre_get_posts', 'query_set_only_author' );

function query_set_only_author( $wp_query ) {
 global $current_user;
 if( is_admin() && !current_user_can('edit_others_posts') ) {
    $wp_query->set( 'author', $current_user->ID );
    add_filter('views_edit-post', 'fix_post_counts');
    add_filter('views_upload', 'fix_media_counts');
 }
}

1

1 Answer 1

1

First, I second Q Studio comment: check Tom McFarlin's post with a warning about using pre_get_posts. More specifically, pre_get_posts works everywhere, including RSS and dashboard, and you might want to exclude your logic from such places.

That said, if I understood correctly what you are trying to do, you can achieve it by using author__in parameter of WP_Query in pre_get_posts.

In fact, the developer documentation have an example:

$query = new WP_Query( array( 'author__in' => array( 2, 6 ) ) );

Your code could be adapted like this:

add_action('pre_get_posts', 'wpse_382339_query_set_only_author' );

function wpse_382339_query_set_only_author( $wp_query ) {
    global $current_user;
    if( is_admin() && !current_user_can('edit_others_posts') ) {
    // 2 is just a placeholder for your user.
        $wp_query->set( 'author__in' , array( 2, $current_user->ID ) );
        add_filter('views_edit-post', 'fix_post_counts');
        add_filter('views_upload', 'fix_media_counts');
    }
}

Bear in mind that this allow users to SEE both their posts and yours. But not edit.

Let me know if it helps or you need more clarification

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.