Support » Fixing WordPress » Display private posts in the WP search results for logged in users

  • Basically as the title says, I put this together a while back in my functions.php and it works:

    // SHOW PRIVATE POSTS FOR LOGGED IN USERS
    function include_password_posts_in_search( $query ) {
    	if ( is_user_logged_in() )
    		$query->set( 'post_status', array ( 'publish', 'private' ) );
    	}
    add_action( 'pre_get_posts', 'include_password_posts_in_search' );

    The only problem is that this chunk of code is conflicting with WP and makes nothing display in my Media section / Individual Posts Gallery. Also I can list posts no problem but when I try to list published or private posts it says “no posts found” when the number of posts still shows there are some.

    So this code is conflicting with something in WP but I can’t figure out what it is!

    Thanks for your time 🙂

Viewing 5 replies - 1 through 5 (of 5 total)
  • Thread Starter dbrunsden

    (@dbrunsden)

    Just to clarify (I missed out an important part)

    This is not working for a custom user role I have set up that has the privileges of:

    read_private_pages
    read_private_posts &
    read

    It works fine as Administrator but not this custom user.

    Thanks

    Thread Starter dbrunsden

    (@dbrunsden)

    Fixed it by putting a is_search loop around it so it only comes into play on the search results page.

    Probably not the best method but seems to work fine.

    Moderator keesiemeijer

    (@keesiemeijer)

    Maybe use some additional conditional checks:
    [untested]

    function include_password_posts_in_search( $query ) {
      // not an admin page and is the main query
      if (!is_admin() && $query->is_main_query()){
        if(is_user_logged_in() && current_user_can('customrole') && is_search()){
          $query->set( 'post_status', array ( 'publish', 'private' ) );
        }
      }
    }
    add_action( 'pre_get_posts', 'include_password_posts_in_search' );

    Change ‘customrole’ to the role want. I’ve added is_search() but I don’t know if you want that.

    Thread Starter dbrunsden

    (@dbrunsden)

    Thanks for your help it seems to work fine with is_search()

    Moderator keesiemeijer

    (@keesiemeijer)

    Ok, I’m glad you got it resolved. Just trying to clarify that is_user_logged_in() will return true for all logged in users no matter what role they have. And that query->is_main_query() will only return true only for the main (search) query.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Display private posts in the WP search results for logged in users’ is closed to new replies.