Support » Fixing WordPress » Restrict posts based on current user in each role (front end)

  • I need an option or code that allows each user in each role to see only their own posts, and completely hide the posts of others, even in search results (without any messages or bookmarks)

    More details:
    The user has to log in to get the content, and when he logs in he only sees his posts (as if there are no other posts on the website)
    Any help would be appreciated
    Thankful

    • This topic was modified 9 months, 3 weeks ago by Jan Dembowski. Reason: Moved to Fixing WordPress, this is not an Developing with WordPress topic
Viewing 3 replies - 1 through 3 (of 3 total)
  • https://developer.wordpress.org/reference/hooks/pre_get_posts/

    function posts_by_current_author( $query ) {
    	$user_id = get_current_user_id();
        if ( ! is_admin() ) {
            $query->set( 'author__in', $user_id );
        }
    }
    add_action( 'pre_get_posts', 'posts_by_current_author' );

    That should work. It’s simple just changing all the post query to only display posts by the current author. Might need some tweaking based on your site but it’s a simple start.

    Thread Starter hamed

    (@gjbyrjyy)

    Thanks for the quick reply

    I want all pages to be excluded (show for all)
    Only hide other users’ posts

    function posts_by_current_author( $query ) {
    	$user_id = get_current_user_id();
    	if ( is_user_logged_in() ) {
    		if ( ! is_admin() ) {
    			$query->set( 'author__in', $user_id );
    		}
    	} else {
    		if ( ! is_admin() ) {
    			$query->set( 'post__in', array(0) );
    		}
    	}
    }
    add_action( 'pre_get_posts', 'posts_by_current_author' );

    if user is not logged in, nothing shows. If user is logged in, only their posts show.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Restrict posts based on current user in each role (front end)’ is closed to new replies.