简体   繁体   English

Wordpress - 仅向帖子作者显示管理栏

[英]Wordpress - Show admin bar only to the post author

I want to show the admin bar on my single.php page ONLY when the actual author of the post is on the page.只有当帖子的实际作者在页面上时,我才想在我的 single.php 页面上显示管理栏。 I took this article as a reference and was able to make the admin bar visible on single.php pages only, but I also want to add a condition to hide it to non-author viewers.我将这篇文章作为参考,并且能够使管理栏仅在 single.php 页面上可见,但我还想添加一个条件以将其隐藏给非作者查看者。 https://second-cup-of-coffee.com/hiding-the-wordpress-admin-bar-on-certain-pages/ https://second-cup-of-coffee.com/hiding-the-wordpress-admin-bar-on-certain-pages/

And this is the code I tried on my functions.php:这是我在函数上尝试的代码。php:

function my_theme_hide_admin_bar($bool) {

  $logged_in_user        =  wp_get_current_user();
  $logged_in_user_id     =  $logged_in_user->ID;

  if ( ! is_single() && $logged_in_user_id !== get_the_author_meta('ID') ) :
    return false;
  else :
    return $bool;
  endif;
}
add_filter('show_admin_bar', 'my_theme_hide_admin_bar');

However, the admin bar still shows when I view a post from another author.但是,当我查看其他作者的帖子时,管理栏仍然显示。

You've got to compare the two ID's, the one from the post author and the one from the current user.您必须比较两个 ID,一个来自帖子作者,一个来自当前用户。 We also want to make sure that the user is an actual author for redundancy.我们还想确保用户是冗余的实际作者。

<?php
add_filter( 'show_admin_bar', function( $show ) {
  if( is_single() && current_user_can( 'author' ) && get_post_field( 'post_author' ) == get_current_user_id() ) {
    return $show;
  } else {
    return;
  };
} ); ?>

EDIT:编辑:

While checking against particular roles in place of a capability is supported in part, this practice is discouraged as it may produce unreliable results.虽然部分支持检查特定角色代替能力,但不鼓励这种做法,因为它可能会产生不可靠的结果。

Having that in mind using current_user_can( 'author' ) isn't considered best practice.考虑到这一点,使用current_user_can( 'author' )不被认为是最佳实践。 Instead an actual capability handle should be used.相反,应该使用实际的能力句柄。 You can refer to the Roles and Capabilities page for a complete list of users and capabilities.您可以参考 角色和功能页面以获取完整的用户和功能列表。

I decided to use the export capability, but you can use anything from Capability vs. Role Table .我决定使用export功能,但您可以使用Capability vs. Role Table中的任何内容。

<?php
  add_filter( 'show_admin_bar', function( $show ) {
    if( is_single() && current_user_can( 'export' ) && get_post_field( 'post_author' ) == get_current_user_id() ) {
      return $show;
    } else {
      return;
    };
} ); ?>

Special thanks to @Xhynk in the comments for the tips and the optimization.特别感谢@Xhynk在评论中的提示和优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM