Archived topic
How to show an element block based on condition is_author()
3 replies · Started by J on June 9, 2021
Hi there,
What would be a good way to conditionally show an element block in a post?
The condition is that the logged-in user is the author of the post that contains the element block. If the logged-in user is the author, then the element would then be shown. And alternatively, if there is no logged-in user or a logged-in user is not the author of the post, the element will not be shown.
Background: I like element blocks. They are easy to create and maintain. Understanding how they can be conditionally switched on and off increases their use.
Thanks for your help.
J
Hi J,
You'll need to use filter for this. For block elements, you can use generate_block_element_display.
Example:
add_filter( 'generate_block_element_display', function( $display, $element_id ) {
global $post;
$author_id = $post->post_author;
if ( 123 === $element_id && is_user_logged_in() && $author_id == get_current_user_id() ) {
$display = true;
}
return $display;
}, 10, 2 );
The contents of the condition is basically:
123 = the element ID of the block element. Change this to the target block element.
get_current_user_id() = the id of the currently logged in user.
$author_id = The ID of the author of the post.
Hi Elvin,
Thanks for your reply. It took me some time but it works!
Important to get this filter working properly is to remove any display rules for the element that you filter for. These rules interfere with the filter and so the element showed on posts where I did not expect it to show.
After removing the display rules, the filter worked fine.
Thanks for you assistance.
J
Glad you got it sorted out. No problem. :)