WordPress 技巧:文章隐藏内容仅限 VIP 用户阅读

资源分享评论15.1K

本文是对用户权限又一次尝试,WordPress 默认的角色(订阅者,投稿者,作者,编辑,管理员)有时候并不是我们的站点需要,这时候就需要自己 DIY 站点角色

WordPress 添加新的角色

将下列代码放置到主题模板函数 functions.php 中,就可以添加一个名为 VIP的用户角色。

add_role('vip', 'VIP会员', array( 'read' => true, // 阅读权限 
'edit_posts' => true, // 编辑权限 
'delete_posts' => false, // 删除权限 ));

WordPress 文章隐藏内容仅限 VIP 用户阅读

1,将下列代码放置到主题模板函数 functions.php 中:

// 限定角色访问权限  
function vip_shortcode( $atts, $content = null ) {  
      if ( is_user_logged_in() &amp;&amp; (current_user_can('<strong><del>vip</del></strong>')||current_user_can('manage_options')) &amp;&amp; !is_null( $content ) &amp;&amp; !is_feed())  
             return $content;  
     return '';  
}  
add_shortcode( 'vip', 'vip_shortcode' );

vip即为添加的自定义角色

2,文章编写隐藏内容

[@vip]VIP 用户可见内容[/@vip] // 去除掉@

下面的情况同样适用于本文自定义角色的应用:

WordPress 技巧:特定角色的搜索结果包含私密文章

WordPress默认情况下,在搜索结果中是不包含加密文章的。本文可以指定角色(role),比方订阅者、编辑、作者等,在其搜索结果中包含私密文章。

将下列代码放置到主题模板functions.php函数闭合中:

// 指定角色登陆后的<a class="tag_link" title="View all posts in 搜索" href="http://tmt.me/tag/%e6%90%9c%e7%b4%a2" target="_blank" rel="noopener">搜索</a>结果包含私密文章  
function include_password_posts_in_search( $query ) {  
    if ( !is_admin() &amp;&amp; $query-&gt;is_main_query() ) {  
        if( is_user_logged_in() &amp;&amp; (current_user_can('<del>customrole</del>')||current_user_can('manage_options')) &amp;&amp; is_search() ) {  
            $query-&gt;set( 'post_status', array ( 'publish', 'private' ) );  
        }  
    }  
}  
add_action( 'pre_get_posts', 'include_password_posts_in_search' );

customrole:修改角色。

WordPress技巧:允许订阅者(subscriber)访问私密文章

在默认的情况下,只有管理员和文章的作者可以访问 WordPress 私密文章。可是有时候我们的私密文章也想让我们的家人,朋友,或者公司同一个 team 成员访问的,可以用插件 WP JV Post Reading Groups来完成。
新建角色 role 配合下面的方法同样可以实现。将下列代码放置到主题模板函数 functions.php 闭合中:

//允许订阅者访问私密文章  
function add_theme_caps() {  
    $subRole = get_role( 'subscriber' );  
    $subRole-&gt;add_cap( 'read_private_posts' );  
    $subRole-&gt;add_cap( 'read_private_pages' );  
}  
add_action( 'admin_init', 'add_theme_caps' );  
//移除、修改标题前的"私密"和"密码保护"  
add_filter( 'private_title_format', 'wp_private_title_format' );  
add_filter( 'protected_title_format', 'wp_private_title_format' );  
function wp_private_title_format( $format ) {  
    return '%s';  
}

评论  0  访客  0

发表评论