5

wordpress登录才能查看网站内容

 2 years ago
source link: https://www.nixonli.com/23490.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
wordpress登录才能查看网站内容 - NixonLi博客

wordpress登录才能查看网站内容,未登录就跳转到登录页面。有这样需求的人还不少,有的可能是资料类什么的,有的人就是用来搞擦边球。

实现代码很简单,找一个全站一定会执行的钩子即可,这里我们就选了一个template_redirect钩子,这个动作钩子在加载模板时执行,当然其它很多都可以用。

  1. <?php
  2. //template_redirect动作钩子是一定会执行的,所以用这个钩子对全站有效
  3. add_action( 'template_redirect', 'ashuwp_show_only_login', 0 );
  4. function ashuwp_show_only_login(){
  5. //判断登录
  6. if( !is_user_logged_in() ){
  7. auth_redirect(); //跳转到登录页面
  8. exit();

更复杂的需求,有人需要整站再留一两个页面,比如留个“公告说明”页面提供访问,那在判断登录的代码里面增加一个页面判断即可,范例:

  1. <?php
  2. //template_redirect动作钩子是一定会执行的,所以用这个钩子对全站有效
  3. add_action( 'template_redirect', 'ashuwp_show_only_login', 0 );
  4. function ashuwp_show_only_login(){
  5. //判断登录,about页面就允许访问
  6. if( !is_page('about') && !is_user_logged_in() ){
  7. auth_redirect(); //跳转到登录页面
  8. exit();

还有其他更奇葩的需求?按照上面的范例加判断条件即可。

完结。
原文链接:https://www.ashuwp.com/courses/supplement/926.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK