2

I have a site with 3 different custom post types (Listings, Contacts, Events) and about 1600 'authors'. What I"m looking to do is only show that author their posts in the backend. So when authorA logs in, and clicks on 'Listings' then they only see their own.

I have this code running in Functions.php to control the first post type, but am not sure how to control the other two. The issue i'm seeing is that when authorA clicks on 'Events', their post that is in 'Listings' show up.

    function __set_all_posts_for_author( &$query )
{
    if ( $query->is_author )
        $query->set( 'post_type', 'listings' );
    remove_action( 'pre_get_posts', '__set_all_posts_for_author' ); // run once!
}
add_action( 'pre_get_posts', '__set_all_posts_for_author' );

So, i think i just need to change 'listings' to all three post types show up but i'm not sure how.... Any thoughts?

1
  • I don't understand this question. The description seems to be different from what the code is attempting. Do you want to make it so that authors only see posts for which they are the author?
    – s_ha_dum
    Aug 16, 2013 at 18:18

2 Answers 2

7

As @s_ha_dum says in his comment, your description and your code seems to be different.

If I understand the description, the code to do what you want is:

function __set_all_posts_for_author( $query ) {
  if ( is_admin() && is_post_type_archive( array('listings', 'contacts', 'events') ) ) {
    $current_user = wp_get_current_user();
    $query->set( 'author', $current_user->ID );
  }
}
add_action( 'pre_get_posts', '__set_all_posts_for_author' );

Using the code above, every time an user that is logged in the backend require items list of CPT 'Listings', 'Contacts' and 'Events' he/she will see only the post created by himself/herself.

2
  • hi, for some reason the is_post_type_archive doesn't work with my 3 cpt names. I try to find, whether is any changes in it's syntax or parameter handling since 2013. Any ideas? Aug 4, 2020 at 18:08
  • i found the problem. In my case i needed this check inside the admin / edit area, that needs a different approach. Aug 5, 2020 at 17:55
-1

You could create an author.php and then grab the author as well as their posts.

<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
query_posts( array(
        'post_type' => array('post','custom_post_type'),
        'author' => $author,
        'posts_per_page' => -1 )
    );
?>

Replace custom_post_type with your CPT name. Use as many as you have/need in the post_type array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.