Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I want to show a list of links to posts for the logged in user on my wp. So I started to do so:

$posts_array = get_posts( array( 'post_type' => 'download', 'post_status' => 'publish' ) );
//$posts_array = apply_filters( 'downloads_shortcode', $posts_array );
foreach($posts_array as $post) {
    setup_postdata($post);
    $title = "<a href=". get_permalink( $post->ID ) . ">" . $post->post_title . "</a>";
    echo $title;
}

But it seems like the function doesn't care about the user capabilities. I use a plugin called "Groups" to require a capability for viewing a post. Everywhere on the page the posts are hidden, if a capability is missing. I'm confused because wp uses get_posts() itself. How to achieve this?

//through Ravs hint I was able to do this approach: I extended the plugin Groups:

add_filter( 'get_posts', array( __CLASS__, "get_posts" ), 1 );
/**
 * Filter posts by access capability.
 *
 * @param array $posts
 */
public static function get_posts( $posts ) {
    $result = array();
    $user_id = get_current_user_id();
    foreach ( $posts as $post ) {
        if ( self::user_can_read_post( $post->ID, $user_id ) ) {
            $result[] = $post;
        }
    }
    return $result;
}

and applied the filter as I already experimented:

$posts_array = apply_filters( 'get_posts', $posts_array );

Thank you.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Use is_user_logged_in

you code may like

$posts_array = get_posts( array( 'post_type' => 'download', 'post_status' => 'publish' ) );
//$posts_array = apply_filters( 'downloads_shortcode', $posts_array );
foreach($posts_array as $post) {
    setup_postdata($post);
  if ( is_user_logged_in() ){
    $title = "<a href=". get_permalink( $post->ID ) . ">" . $post->post_title . "</a>";
    echo $title;
  }
  else{
    // do something
  }
}

Note:If you want to show post link depand upon user login and their role or capabilities use current_user_can

share|improve this answer
    
Thanks for this hint. I could find the according part in the Groups plugin and was able to extend it. @See my approach in the first post. –  No3x May 22 '13 at 13:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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