根据页面模板将未登录用户重定向到特定页面

时间:2017-07-06 作者:Odell

如果所有未登录的用户直接尝试访问以下内容,我希望将其重定向到特定页面:

我试图在子主题的functions.php, 但它不起作用。

add_action( \'template_redirect\', \'redirect_to_specific_page\' );
function redirect_to_specific_page() {
    if ( is_page_template( \'single-post\' ) && ! is_user_logged_in() ) {
        wp_redirect( \'/\', 301 );
        exit;
    }
}

1 个回复
最合适的回答,由SO网友:Dave Romsey 整理而成

下面是代码的更新版本,当用户尝试查看标签或类别存档或单个帖子时,它会成功地将未登录到特定页面的用户重定向到该页面。

add_action( \'template_redirect\', \'wpse_redirect_to_specific_page\' );
function wpse_redirect_to_specific_page() {
    // Bail if the user is logged in.
    if ( is_user_logged_in() ) {
        return;
    }

    // Redirect to a special page if the user is trying to access
    // a category or tag archive or a single post.
    if ( is_category() || is_tag() || is_singular( \'post\' ) ) {

        // Set the ID of the page to redirect to.
        // Change the ID to the desired page to redirect to.
        $redirect_to_page_id = 1086;

        wp_safe_redirect( get_permalink( $redirect_to_page_id ), 301 );
        exit;
    }
}

Handling custom taxonomies

如果要重定向自定义分类法归档页面,可以添加is_tax() 到封装重定向代码的条件语句。

Handling custom post types

如果您想对所有post类型的单数页执行相同的操作,可以使用is_singular() 未通过post 参数,或对于特定的帖子类型,传递一个帖子类型名称数组。

结束

相关推荐