仅显示登录用户+我的帖子所拥有的帖子

时间:2021-01-28 作者:Cedric

我想限制登录用户访问特定帖子:他们自己的帖子和我的帖子(因为它们将作为他们的模板)。

我发现这个代码片段非常适合向他们展示自己的帖子,但我希望他们也能看到我的帖子。你知道我怎么做吗?如何更新此代码以使其按我的意愿工作?

非常感谢您的帮助。非常感谢……;-)

<小时/>

add_action(\'pre_get_posts\', \'query_set_only_author\' );

function query_set_only_author( $wp_query ) {
 global $current_user;
 if( is_admin() && !current_user_can(\'edit_others_posts\') ) {
    $wp_query->set( \'author\', $current_user->ID );
    add_filter(\'views_edit-post\', \'fix_post_counts\');
    add_filter(\'views_upload\', \'fix_media_counts\');
 }
}
<小时/>

1 个回复
SO网友:Celso Bessa

第一,我第二个Q工作室评论:检查Tom McFarlin\'s post 带有关于使用pre\\u get\\u帖子的警告。更具体地说,pre_get_posts 在任何地方都可以使用,包括RSS和dashboard,您可能希望从这些地方排除您的逻辑。

也就是说,如果我正确理解了您要做的事情,您可以使用author__in 的参数WP_Query 在里面pre_get_posts.

事实上,开发人员文档有一个示例:

$query = new WP_Query( array( \'author__in\' => array( 2, 6 ) ) );
您的代码可以进行如下调整:

add_action(\'pre_get_posts\', \'wpse_382339_query_set_only_author\' );

function wpse_382339_query_set_only_author( $wp_query ) {
    global $current_user;
    if( is_admin() && !current_user_can(\'edit_others_posts\') ) {
    // 2 is just a placeholder for your user.
        $wp_query->set( \'author__in\' , array( 2, $current_user->ID ) );
        add_filter(\'views_edit-post\', \'fix_post_counts\');
        add_filter(\'views_upload\', \'fix_media_counts\');
    }
}
请记住,这允许用户同时查看他们的帖子和您的帖子。但不能编辑。

如果有帮助或需要更多说明,请告诉我

相关推荐