强制用户在阅读WordPress中的帖子之前先登录

If your blog has some restricted area that you don’t want to publicize to all visitors, just for members only, then you might want to force users to login before reading these posts. Fortunately, WordPress has a built-in function which can help us to do that.

如果您的博客有一些限制区域,您不想将其发布给所有访问者(仅针对成员),那么您可能希望在阅读这些帖子之前强迫用户登录 。 幸运的是,WordPress具有内置功能,可以帮助我们做到这一点。

WordPress: Force Users To Login Before Reading Posts

The function is auth_redirect(), this is how it works: When it is called from a page, it checks to see if the user viewing the page is logged in. If the user is not logged in, they are redirected to the login page. The user is redirected in such a way that, upon logging in, they will be sent directly to the page they were originally trying to access.

该函数是auth_redirect() ,其工作方式如下:当从页面调用该函数时,它将检查查看该页面的用户是否已登录。如果该用户未登录,则将他们重定向到登录页面。 。 重定向用户的方式是,登录后将其直接发送到最初尝试访问的页面

By using this function, we can implement our code that check if post is restricted or not, and redirect users to login page if needed.

通过使用此功能,我们可以实现检查帖子是否受到限制的代码,并在需要时将用户重定向到登录页面。

Just paste the following code into your theme’s functions.php file:

只需将以下代码粘贴到主题的functions.php文件中:


    function my_force_login() {
    global $post;

    if (!is_single()) return;

    $ids = array(188, 185, 171); // array of post IDs that force login to read

    if (in_array((int)$post->ID, $ids) && !is_user_logged_in()) {
    auth_redirect();
    }
    } 

Change the array of post IDs to fit your requirement. After that, open the header.php file and put the following code in the very top:

更改帖子ID的数组以适合您的要求。 之后,打开header.php文件,并将以下代码放在最顶部:


<?php my_force_login(); ?>

The code is simple, but you can expand it with more options like: require login in some specific categories, make an option page for easy input post IDs, etc.

代码很简单,但是您可以使用更多选项来扩展它 ,例如:要求登录某些特定类别,创建选项页面以方便输入帖子ID等。

The function auth_redirect() is available since WordPress 1.5.

从WordPress 1.5开始,功能auth_redirect()就可用了。

Tuan AnhTuan Anh (aka. Rilwis) is a 25 years old blogger and web developer from Vietnam. He is interested in PHP, MySQL as well as Web 2.0 technologies (CSS, Javascript, Ajax). He loves WordPress and all related to it. Follow Rilwis on Tuan Anh(又名Rilwis)是来自越南的25岁博客和网络开发人员。 他对PHP,MySQL以及Web 2.0技术(CSS,Javascript,Ajax)感兴趣。 他喜欢WordPress及其所有相关内容。 在
TwitterTwitter上 Deluxe Blog Tips豪华博客提示

翻译自: https://www.wpbeginner.com/wp-tutorials/force-users-to-login-before-reading-posts-in-wordpress/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值