Language:

Search

Show posts for the current author only - WordPress

  • Share this:
Show posts for the current author only - WordPress

If you're running a blog or a magazine & a number of authors are working for you & writing for your blog on a daily basis. You'd probably want the current author to view their posts only in the dashboard. Which by default is not built-in the WordPress. Each author can view the posts of other authors (obviously they can't edit it) but for a large-scale blog or a magazine, this might create a mess in the author's dashboard.

To prevent this issue, just place the following snippet into your theme's function.php & see the magic for yourself.

function posts_for_current_author($query) {
    global $pagenow;

    if( 'edit.php' != $pagenow || !$query->is_admin )
        return $query;

    if( !current_user_can( 'edit_others_posts' ) ) {
        global $user_ID;
        $query->set('author', $user_ID );
    }
    return $query;
}
add_filter('pre_get_posts', 'posts_for_current_author');

What this piece of code does?

If you see here, we're using pre_get_posts hook, which runs before the actual query is run. We're checking whether the current_user_can() has the capability of edit other posts & set the query accordingly. Simple enough? eh?

Try it  yourself & let us know if you get stuck somewhere in between.

Usama Muneer

Usama Muneer

A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.