WordPress 只允许已登录的用户查看文章内容 [简码]

网站的注册用户是最有价值的访问者,这些人都是忠实的访客,我们应该奖励他们。其中一个奖励的措施,就是给注册用户分享最新的优质内容。也就是说,可以在某些文章中隐藏部分优质的内容,要求访问登录后才可以查看,这也是鼓励用户注册网站的方法之一。下面就来说说如何实现这个功能。

我们都知道,WordPress 有一个很棒的功能——简码(shortcode),我们可以利用简码来实现。关于简码,不熟悉的朋友可以先阅读《WordPress Shortcode(简码)介绍及使用详解》。

下面就是我们的代码示例,你可以添加到一个插件中,或者添加到主题的 functions.php:

/**
 * WordPress 只允许已登录的用户查看文章内容
 * https://www.wpdaxue.com/registered-content-shortcodes.html
 */
add_shortcode( 'members_only', 'members_only_shortcode' );
function members_only_shortcode( $atts, $content = null ) 
{
    if ( is_user_logged_in() && !empty( $content ) && !is_feed() )
    {
        return $content;
    }
 
    return '要查看文章内容,请先登录。';
}

在上面的代码中,我们注册了一个简码 [members_only] ,在简码的函数中,我们使用了 is_user_logged_in() 函数来判断当前访问者是否登录,同时使用 !empty( $content ) 确保内容不为空,使用 !is_feed() 排除在RSS订阅中输出。

这样一来,我们可以在文章中使用简码添加内容:

[members_only]
 
这里的内容只为已登录的用户显示
 
[/members_only]

如果当前访问者没有登录,就显示“要查看文章内容,请先登录。”,反之,则显示添加的内容“这里的内容只为已登录的用户显示”。

需要注意的是,你必须确保上面的函数代码不要被删除,否则所有简码包含的内容都会直接显示出来哦!

来源:

https://www.wpdaxue.com/registered-content-shortcodes.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_33117.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?