This tutorial explains how to limit the display of posts to the currently logged-in post author. This is useful when you have a mutli-author blog where each author should only be able to view and edit their own posts. This technique works with or without USP Pro.

Method 1

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). Simply add the following snippet to your theme’s functions.php:

// limit post display to post author (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');

That will allow any admin-level users to see all posts; all other users will only see the posts they have written if they are logged into the site. To change it so that admins too can only see their own posts, check out the next method.

Method 2

To do the same thing as the previous method, but also limit post display to admin-level users, use this function instead:

// limit post display to post author (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');

As with the previous function, this code sets the post query so that only posts from the current logged-in author are returned.

For either of these methods, make sure to test well, all cases (logged in, logged out), different users, etc) before going live. The techniques are solid, but only tested on default WP installations. So if you are running a bunch of plugins, you’re gonna want to test everything for proper functionality.

Bonus: Ignore Pages

A user asked how to ignore pages in the above code techniques. For example, all users should have full access to all static WP Pages (like the About Page, Contact Page, etc.). To do this, we use is_page(), like so:

// limit post display to post author (excludes admins)
function shapeSpace_set_only_author($query) {
	global $current_user;

	if (is_page()) return; // <---

	if (!current_user_can('manage_options')) {
		$query->set('author', $current_user->ID);
	}
}
add_action('pre_get_posts', 'shapeSpace_set_only_author');

So with that line included, it tells WordPress to check if the current request is for a static page, and if so do nothing (return).