允许订阅者角色删除自己的帖子

时间:2017-05-31 作者:frshjb373

我正在尝试允许订阅者角色使用以下代码删除自己的帖子:

<?php if ($post->post_author == $current_user->ID) { ?>
    <div class="col-sm-12 box-delete" style="margin-top: 20px;">
        <a class="option" onclick="return confirm(\'Are you sure you want to delete <?php the_title();?>\')" href="<?php echo get_delete_post_link( $post->ID ) ?>">
            <i class="fa fa-trash"></i>
            <span class="option-text">Delete</span>
        </a>
    </div>
<?php } ?>
我使用的是用户角色编辑器,但它只有在我授予对所有核心角色的访问权限时才起作用,这使订阅者能够访问后端,这是我当然不想要的。有没有其他想法或解决方案来实现这一点?

2 个回复
SO网友:Nathan Johnson

删除帖子所需的功能是delete_posts. 如果您希望他们能够删除自己发布的帖子,那么该功能是delete_published_posts.

查看管理面板所需的功能是read. 订阅者本机具有此功能,因此除非您将其删除,否则订阅者可以访问后端。

我将编写一个简单的插件,在激活时为订阅者角色添加所需的功能,在停用时删除这些上限。

然后在主题中,您可以检查:

if( current_user_can( \'delete_posts\' ) ) {
  //* Show delete link
}
因为订阅服务器角色无法delete_others_posts, 该链接将不会显示在他们没有创作的帖子上,并且他们将无法删除他们没有发布的帖子。

/**
 * Plugin Name: WordPress StackExchange Question 268755
 * Description: Allow subscribers to delete their own posts
 **/

//* On activation, add the capabilities to the subscriber role
register_activation_hook( __FILE__, \'wpse_268755_activation\' );
function wpse_268755_activation() {
  $subscriber = get_role( \'subscriber\' );
  $subscriber->add_cap( \'delete_posts\' );
  $subscriber->add_cap( \'delete_published_posts\' );
}

//* On deactivation, remove the capabilities from the subscriber role
register_deactivation_hook( __FILE__, \'wpse_268755_deactivation\' );
function wpse_268755_deactivation() {
  $subscriber = get_role( \'subscriber\' );
  $subscriber->remove_cap( \'delete_posts\' );
  $subscriber->remove_cap( \'delete_published_posts\' );
}
如果不给用户和/或角色删除帖子的能力,那么即使您向他们显示删除链接,他们也无法删除帖子。同样,如果用户或角色有能力删除帖子,即使你没有显示删除链接,也可以删除帖子,这对他们来说只是更加困难。

SO网友:Sam

您应该能够调整以下内容以满足您的需要,只需确保为订阅者角色选择delete\\u posts选项,这将允许他们只删除自己的帖子。

以下内容可以添加到您的单曲中。显示帖子的php或php文件,以便在内容下提供删除帖子按钮。

// Check the user is author and has a role ID of subscriber as they don\'t have by default the delete post privilege but you can use the user role editor to allow subscribers to be able to delete there own posts and then add this code into your file where required on the post single page.


     if ( get_the_author_meta(\'ID\') == get_current_user_id() && current_user_can(\'subscriber\') )
              {
                // owner of post and subscriber
                get_delete_post_link( $post->ID );
              }
              if ( get_the_author_meta(\'ID\') != get_current_user_id()  && current_user_can(\'subscriber\')  )
              {
                // not the owner of post and subscriber
                echo \'Not your post\';
              }
              else
              {
               // should be ok as not a subscriber and has delete privilages
               get_delete_post_link( $post->ID );
              }

结束

相关推荐