【问题标题】:Wordpress - Show admin bar only to the post authorWordpress - 仅向帖子作者显示管理栏
【发布时间】:2021-04-11 11:29:09
【问题描述】:

我只想在帖子的实际作者在页面上时才在我的 single.php 页面上显示管理栏。 我将这篇文章作为参考,并且能够使管理栏仅在 single.php 页面上可见,但我还想添加一个条件以将其隐藏给非作者查看者。 https://second-cup-of-coffee.com/hiding-the-wordpress-admin-bar-on-certain-pages/

这是我在 functions.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');

但是,当我查看其他作者的帖子时,管理栏仍然显示。

【问题讨论】:

标签: php wordpress


【解决方案1】:

您必须比较两个 ID,一个来自帖子作者,一个来自当前用户。我们还想确保用户是冗余的实际作者。

Function Description
get_post_field( 'post_author' ) Retrieve data from a post field based on Post ID.
get_current_user_id() Get the current user’s ID.
current_user_can( 'author' ) Returns whether the current user has the specified capability.
<?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;
  };
} ); ?>

编辑:

虽然部分支持检查特定角色来代替能力,但不鼓励这种做法,因为它可能会产生不可靠的结果。

考虑到这一点,使用current_user_can( 'author' ) 不被视为最佳做法。相反,应该使用实际的能力句柄。您可以参考Roles and Capabilities page 获取完整的用户和功能列表。

我决定使用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;
    };
} ); ?>

特别感谢 cmets 中的 @Xhynk 提供提示和优化。

【讨论】:

  • $post_id 未在 show_admin_bar 过滤器的范围内定义。您需要使用get_the_ID()global $post; $post-&gt;ID;。否则,+1(我也挖掘了表函数参考,我可能会开始使用它)
  • 另外,由于返回值是双条件的,is_single() 检查可以组合成一个返回三元组:return (is_single() &amp;&amp; get_post_field('post_author', get_the_ID()) == get_current_user_id()) ? $show : false; - 如果不是单个或不是帖子的所有者,则返回 false,否则返回他们的个人设置值。
  • 哇,我早上(下午早些时候)咖啡还在工作,哈哈。这是因为它作为null 传递,get_post_field() 将假定global $post 来自。所以你可以只用get_post_field( 'post_author' )替换它,不需要第二个参数!
  • 非常感谢@amarinediary 和@Xhynk!我尝试了提供的代码,但一开始没有用,但我删除了第二个条件current_user_can( 'author' ),它工作了!这可能是因为我使用 Ultimate Member 插件为作者使用了自定义角色。如果您能指出基于此删除的任何潜在问题,我们将不胜感激。再次感谢!
  • 没错,我把它添加为冗余,通常你想避免更改 Wordpress 默认权限。
猜你喜欢
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 2012-02-08
  • 2020-03-16
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多