我想在我的wp上显示登录用户帖子的链接列表。所以我开始这样做:
$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;
}
但功能似乎并不关心用户的能力。我使用一个名为“组”的插件来要求具有查看帖子的功能。如果功能缺失,页面上的所有帖子都会被隐藏。我很困惑,因为wp本身使用get\\u posts()。如何做到这一点?
//通过Ravs提示,我能够做到这一点:我扩展了插件组:
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;
}
并应用了我已经试验过的过滤器:
$posts_array = apply_filters( \'get_posts\', $posts_array );
谢谢你。
最合适的回答,由SO网友:Ravinder Kumar 整理而成
使用is_user_logged_in
您的代码可能会喜欢
$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:如果要在用户登录时显示post link depand及其角色或功能,请使用
current_user_can