Ask your WordPress questions! Pay money and get answers fast! (more info)

Show authors only their custom post types WordPress

  • SOLVED

I've got a custom post type called "dealer."

I need to only let authors see the custom post types they are authors of. Currently I'm using Justin Tadlock's members plugin to define a role that doesn't allow them to edit other CPTs, but I don't want them to see them at all.

Can someone give me the code for functions.php to make this work? Or is it more advanced?

The attached image shows the custom post types view, and it's showing all of them for this particular user.

Thanks!

Site specs:

WordPress 4.1
Roots Starter Theme 6.5
Custom post types defined in functions.php file without using plugin

Answers (2)

2015-02-02

timDesain Nanang answers:

try this:

add_action('pre_get_posts', 'wpq_restrict_post_by_author');
function wpq_restrict_post_by_author( $query ) {
global $user_ID;

if( is_admin() AND $query->is_main_query() AND !current_user_can('edit_users') ){
$query->set('author', $user_ID );
}

return;
}


or with cpt:

add_action('pre_get_posts', 'wpq_restrict_post_by_author');
function wpq_restrict_post_by_author( $query ) {
global $pagenow, $user_ID;
$post_type = get_current_screen()->post_type;

if( is_admin() AND $query->is_main_query() AND $post_type=='dealer' AND !current_user_can('edit_users') ){
$query->set('author', $user_ID );
}

return;
}



you can change this part
!current_user_can('edit_users')
with
!current_user_can('administrator')


Kyler Boudreau comments:

timDesain,

Thank you! Your solution worked beautifully.


Kyler Boudreau comments:

timDesain,

One question -- I just realized that your code is applying to all post types on the entire site now. I need it to just apply to the "dealers" custom post type. Is that possible?

2015-02-02

Romel Apuya answers:

try this

add_action('pre_get_posts', 'filter_posts_listing_dealer');
function filter_posts_listing_dealer($query)
{
global $pagenow;
global $current_user;
get_currentuserinfo();

if(!current_user_can('administrator') && current_user_can('edit_posts') && ('edit.php' == $pagenow) && is_post_type_archive('dealer'))
{
$query->set('author', $current_user->ID);
}
}


Kyler Boudreau comments:

Romel,

Just a heads up, your code adds a "Mine" filter, but it doesn't hide the others if that user clicks on "All" or "Published."

Thanks man.

- kyler