I want to show the admin bar on my single.php page ONLY when the actual author of the post is on the page. 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. 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:
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.
Advertisement
Answer
You’ve got to compare the two ID’s, the one from the post author and the one from the current user. We also want to make sure that the user is an actual author for redundancy.
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; }; } ); ?>
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. 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.
<?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.