【问题标题】:Redirect to URL if the user isnt the author of the post如果用户不是帖子的作者,则重定向到 URL
【发布时间】:2019-05-17 12:08:47
【问题描述】:

我正在寻找一种在查看任何出版物时重定向的方法,但出版物的作者除外。

“作者”和“custom_role”站点中有两个角色。允许最后一个角色查看所有内容。 作者的角色只能看到他自己的,其余的重定向。 我已经尝试了一段时间,在最后一个代码中我正在工作,但它不起作用,我不知道为什么

非常感谢!

add_action( 'pre_get_posts', function() {
if( is_author() )
{
    if( ! is_user_logged_in() )
    {
        wp_redirect( 'https://aaa.com/custom' );
        exit;
    }

    $author = get_queried_object();

    if( $author->ID != get_current_user_id() )
    {
        wp_redirect( get_author_posts_url( 
 get_current_user_id() ) );
        exit;
    }

}
} );

【问题讨论】:

    标签: wordpress roles


    【解决方案1】:

    首先,is_author() 用于检查当前页面是否为作者存档页面。请检查以下示例。这可能不是确切的anster,但它可能会有所帮助。在单个帖子中,比较帖子作者和当前用户 ID。如果它们不相同,则将其重定向到主页。如果这些ID相同,则当前用户也是帖子作者,因此将允许当前用户查看页面。

    add_action( 'get_header', 'wpso_author_redirection' );
    
    function wpso_author_redirection() {
        if ( is_singular() ) {
            $current_post_details = get_post( get_the_ID(), ARRAY_A );
            $user_id = get_current_user_id();
            if ( $user_id !== absint( $current_post_details['post_author'] ) ) {
                wp_redirect( home_url() );
            }
        }
    }
    

    【讨论】:

    • 嗨尼兰巴尔!感谢您的回答。我试过这个,但它破坏了网站。 ERR_TOO_MANY_REDIRECTS 可能是我应该更改 get_header?
    • 抱歉,不知道为什么会这样。它在我的设置中运行良好。好的,让我们等待其他答案。
    • 我将 is_singular 更改为 is_single 并且这行得通!非常感谢!!我该如何添加对 shop_manager 的权限?我试过这个if ( $user_id !== absint( $current_post_details['post_author'] ) || $user['roles']== 'shop_manager' ) { wp_redirect( home_url() ); 但它不起作用
    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多