需要登录特定页面

时间:2016-02-24 作者:john sahhar

我的header.php 从页面数组中排除标头的文件。代码如下所示:

<?php if ( ! is_page( array ( 3599,3653,3684,3732,3737,3758, 3769 ) ) ) { ?>

<?php
对于相同的页面阵列,我需要有人登录才能查看它们。在这行代码中,我是否可以实现一些只适用于那些页面的东西,以便人们需要登录,如果没有,它会将他们重定向到登录页面?如果他们确实登录了,那么应该将他们重定向到他们最初尝试查看的页面。

我试图创建自定义模板来实现这一点,所以我认为这可能是最好的方法。我尝试了几行代码,例如:

get_currentuserinfo();
global $user_ID;
if ( $user_ID == \'\' ) {
    header( \'Location: /wp-login.php\' ); 
    exit(); 
}

1 个回复
SO网友:N00b

你想得太多了(very dangerous and harmful for programmer/developer )..

只需在页面模板中使用以下逻辑:

<?php

//Check if user is logged in
if( is_user_logged_in() ) {

    //The the stuff you want to show to logged-in users
}
else {

    //Do something else, e.g show notice "You have to be logged in to view this content"
}

?>

Redirecting is a very bad idea because people will get confused easier than you might think!

如果我点击一个链接,它会在没有任何通知的情况下将我重定向回来,我会再试一次。。以防万一。。Then I will leave your site 并且可能会与其他人分享我的糟糕经历,因为这感觉像是在嘲笑。



IF 您正在谈论帖子(不要将其与页面混淆),我建议您:

使用复选框将元框添加到帖子编辑屏幕,如果帖子已保存,则将复选框值另存为帖子元复选框用作标志:如果选中,则仅向登录用户显示帖子。

然后,您的帖子模板(single-{post type}.php)中的代码如下所示:

<?php

//Get the post meta from database    
$user_flag = get_post_meta( $post_id, \'user_flag\', \'true\' );


//Check if checkbox was checked and user is logged in
//                      OR
//If it was not checked, show content to everybody
if( ! $user_flag || $user_flag && is_user_logged_in() ) {


    //The the stuff you want to show to logged-in users
}
else {

    //Do something else, e.g show notice "You have to be logged in to view this content"
}

?>