dongzheng4556 2016-02-18 12:38
浏览 54
已采纳

wordpress重定向到登录表单

I know that are some answers to my question but i don't know if my problem exists in the other persons who asked for help.

I have this function that helps me to redirect users to login before access any contetnt of my website:

    function restrict_access_if_logged_out(){
    if (!is_user_logged_in() && !is_home()){
        wp_safe_redirect(wp_login_url(get_permalink()));
    }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );

That function works fine but i have a problem. When somebody is navigated to my home page and click to a link that goes here: 'example.com/about' then my function works great. When somebody he trying to go direct to 'example.com/about' by entering this into browser url then my function doesn't work and he is able to access my website. What i have do wrong? I have write my function in my templates function.php file.

I just created a page template called restriction_page.php:

<?php
/*
Template Name: My Restricted Page
*/
?>

<h1>Hello There</h1>

<?php
function restrict_access_if_logged_out(){
    if (!is_user_logged_in() && !is_home()){
        wp_safe_redirect(wp_login_url());
    }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );
 ?>

i set this template as the fefault template in my about page. No solution.

Any ideas?

  • 写回答

3条回答 默认 最新

  • dongli8862 2016-02-18 14:49
    关注

    Method :1 you can add it to the top of page.php

    If you want to add more pages, just add the ||(or) operator like so:

    <?php
    $pageTitle == get_the_title();
      if($pageTitle == 'Submit' || $pageTitle =='NewPage') {
           if (!is_user_logged_in()) {
             redirect code
         } else {
             page code
         }
      } else {
      page code
    }
    ?>
    

    Method:2

    Write this into a plugin:

    add_action( 'template_redirect', 'auth_redirect' );
    

    This will force all visitors login if they aren’t already.

    In some cases, this is asking for a log-in every time. This might work better:

    add_action( 'template_redirect', function() {
        is_user_logged_in() || auth_redirect();
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值