skip to Main Content

I have created a custom post type (CPT) in WordPress that I’ve made available to logged in users that have a new custom role.

When such a user logs into wp-admin they are shown the list of CPTs – at https://example.org/wp-admin/edit.php?post_type=my_cpt – in the usual way.

So, on that page, they can select whether to filter the CPT list by "All", "Mine", "Published", "Pending" and "Bin".

What I would like is so that they only see their own CPT posts and not anyone elses. How can I achieve this without using a CSS hack?

2

Answers


  1. Chosen as BEST ANSWER

    @Codeschreiber.de (or anyone else), is this how the $pagenow global should be used, if at all??

    /**
     * Filter so, in wp-admin, logged in users can only see their own CPTs,
     * but admins can still see all CPTs.
     * @global type $pagenow
     * @param type $query
     */
    public function filter_by_author( $query ) {
    
        global $pagenow;
    
        if ( ($pagenow === 'edit.php' && isset( $_GET['post_type'] ) && 'my_cpt' === $_GET['post_type'] )
            && wp_get_current_user()->roles[0]  !== 'administrator' // Administrators should be able to see all CPTs
            ) {
    
        $query->query_vars['author'] = get_current_user_id();
        }
    }
    

  2. this function make it happen:
    add a filter to the admin query, which always set the author to current user.

    add_filter( 'parse_query', 'filter_by_author' );
    
    function filter_by_author($query)
    {
        global $pagenow;
        if (isset($_GET['post_type'])
            && $pagenow === 'edit.php'
            && 'my_cpt' == $_GET['post_type']
            && is_admin()
            && wp_get_current_user()->roles[0]  !== 'administrator'
        ) {
            $query->query_vars['author'] = get_current_user_id();
        }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search