Boycott A.I.
Boycott A.I.

Reputation: 18881

How to show Custom Post Types in WordPress admin / wp-admin that were created by current user only?

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?

Upvotes: 0

Views: 1623

Answers (2)

Titus
Titus

Reputation: 806

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();
    }
}

Upvotes: 1

Boycott A.I.
Boycott A.I.

Reputation: 18881

@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();
    }
}

Upvotes: 0

Related Questions