Show posts for the current author only – WordPress

Last Updated at : September 5, 2017 By - Usama Muneer | 1663

    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.

    blog user
    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.

    Related Posts

    If you are running any business on the online platform, then you might know that both of these concepts are important, and play a significant role in this technology-prone era.

    You are in constant danger. Maybe you do not realise. Maybe you are very naive and you think you are not going to attack, because you have nothing important to be attacked.

    We're not web designers, but rather we comprehend what it takes to make an extraordinary website utilising WordPress. Gratefully, we've been sufficiently fortunate to discover a huge amount of extraordinary web designers who know their stuff

    Once you become the owner of your WordPress’s website, you accept the ownership and try to build it in every way possible. But doing it the wrong way can leave you barehanded in the end. Yes, we are talking about the shortcuts that are mostly illegal and overlooks privacy.