Show posts for the current author only – WordPress

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

    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

    Very few things have disrupted the digital marketing scene as greatly as WordPress has in the last decade. Thanks to the platform’s free and simple content management system it made it possible for anyone, regardless of levels of technical knowledge, to create impressive websites.

    Modern brands have an entire selection of platforms which they can use to build their online presence and establish themselves as a relevant entity in their industry, and yet, WordPress remains high on the list of platforms most frequently chosen for precisely this purpose.

    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.