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 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示