简体   繁体   English

如何要求在带有短码的wordpress页面上登录

[英]How to require a login on a wordpress page with a shortcode

When I attempt the following I get Warning: Cannot modify header information - headers already sent by...... 当我尝试以下操作时,我得到警告:无法修改标题信息-标题已由...发送...

I'm trying to require a user to be logged in before they access my page with the shortcode on it. 我试图要求用户先登录,然后才能访问上面带有短代码的页面。

What am I missing? 我想念什么? Thanks a million for any help you can offer. 感谢您提供的一百万美元的帮助。

add_shortcode( 'guest-posts', 'guestposts_shortcode' );

function guestposts_shortcode( $atts ) {
    auth_redirect();
}

It may work if you parse the post content before to render it. 如果您在发布之前解析帖子内容,则可能会起作用。 Then you should check if you find the shortcode inside the content. 然后,您应该检查是否在内容中找到了简码。

Here is a small generic function to check it : 这是一个小的通用函数来检查它:

function has_shortcode($shortcode = '') {
    global $post;

    if (!$shortcode || $post == null) {  
        return false;  
    }

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

    return false;
}

Now we have to create a function that will check for our specific shortcode : 现在我们必须创建一个函数来检查我们的特定短代码:

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

Then we have to hook our function (I think this can work in "wp" hook, but you can try anohter if it does not) : 然后,我们必须挂接我们的函数(我认为这可以在“ wp”挂接中工作,但是如果不能,可以尝试使用anohter):

add_action('wp', 'unlogged_guest_posts_redirect');

To finish, we have to ensure that the shortcode won't echo anything : 最后,我们必须确保简码不会回显任何内容:

add_shortcode( 'guest-posts', 'guestposts_shortcode' );

function guestposts_shortcode( $atts ) {
    return false;
}

Actually we are dealing with shortcodes but we're not using the WordPress shortcode API . 实际上,我们正在处理简码,但未使用WordPress简码API This functionnality should be done using a custom field , it would be simpler ! 应该使用自定义字段来完成此功能,这会更简单!

You could instead create a special category, and hook into template_redirect : 您可以创建一个特殊的类别,然后挂接到template_redirect

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM