1

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.

1

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

  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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