如何要求登录一个短代码的wordpress页面


How to require a login on a wordpress page with a shortcode

当我尝试以下操作时,我得到警告:无法修改标头信息-标头已由......发送

我试图要求用户登录之前,他们访问我的网页与短代码。

我错过了什么?万分感谢你能提供的任何帮助。

add_shortcode( 'guest-posts', 'guestposts_shortcode' );
function guestposts_shortcode( $atts ) {
    auth_redirect();
}

如果在渲染之前解析文章内容,可能会起作用。然后你应该检查你是否在内容中找到了短代码。

这里有一个小的泛型函数来检查它:

function has_shortcode($shortcode = '') {
    global $post;
    if (!$shortcode || $post == null) {  
        return false;  
    }
    if ( stripos($post->post_content, '[' . $shortcode) !== false ) {   
        return true;
    }
    return false;
}

现在我们必须创建一个函数来检查我们的特定短代码:

function unlogged_guest_posts_redirect() {
    if(has_shortcode('guest-posts') && !is_user_logged_in()) {
        auth_redirect();
    }
}

然后我们必须挂钩我们的函数(我认为这可以在"wp"挂钩,但你可以尝试另一个,如果它不):

add_action('wp', 'unlogged_guest_posts_redirect');
最后,我们必须确保短代码不会回显任何内容:
add_shortcode( 'guest-posts', 'guestposts_shortcode' );
function guestposts_shortcode( $atts ) {
    return false;
}

实际上我们正在处理短代码,但我们没有使用WordPress短代码API。此功能应该使用自定义字段来完成,这会更简单!

您可以创建一个特殊的类别,并钩入template_redirect:

add_filter('template_redirect', function() {
    if (is_single() && in_category('special') && !is_user_logged_in())
        wp_redirect(site_url('/wp-login.php'));
});
相关文章: