WP-Mix

A fresh mix of code snippets and tutorials

WordPress Limit Post Display to Post Authors

Here is a good, WP-API method of limiting post display to the currently logged-in post author (i.e., so users can only view their own posts). Here you’ll find two variations of this technique. The first limits the display of posts for non-admin users only. The other limits the display of posts for all users, including admins.

Display only posts from logged-in post author (excluding admins)

To restrict the posts that each logged-in author can view on the front-end, add the following snippet to your theme’s functions.php:

// limit post display to post authors (excludes admins)
function shapeSpace_set_only_author($query) {
	global $current_user;
	if (!current_user_can('manage_options')) {
		$query->set('author', $current_user->ID);
	}
}
add_action('pre_get_posts', 'shapeSpace_set_only_author');

Here we are using pre_get_posts to modify the post query, such that only non-admins will be able to view only their own posts. So it will allow any admin-level users to see all posts, while all other users will be able to view only the posts for which they are the author.

Display only posts from logged-in post author (including admins)

We can modify the previous technique to limit post display for admin-level users as well. So all users including admins will only be able to view their own posts. To do so, we can remove a couple of lines, like so:

// limit post display to post authors (includes admins)
function shapeSpace_set_only_author($query) {
	global $current_user;
	$query->set('author', $current_user->ID);
}
add_action('pre_get_posts', 'shapeSpace_set_only_author');

Make sure to test well, all cases (logged in, logged out, different users, etc). Should work fine as-is, but you need to mindful of any other related things that your theme or plugins may be doing. Should definitely be enough to get you going in the right direction.

Learn more

WordPress Themes In Depth