Archived topic
Show block only to author of post
5 replies · Started by Laura on February 3, 2022
Is there a way in GenerateBlocks to only show a block to the logged in author of the post and the administrator role?
Thanks in advance.
Laura
Hi Laura,
Sorry, but there isn’t a functionality to solely hide or show blocks from GenerateBlocks itself depending on the user.
Element have this functionality though: https://share.getcloudapp.com/OAu4lqz0
If you wish to push through with having individual blocks appear or disappear at any location depending on the current User, one approach you can try is to have a portable Hook shortcode:
function your_shortcode($atts, $content = null) {
ob_start();
do_action('your_hook_name');
return ob_get_clean();
}
add_shortcode('shortcode_name', 'your_shortcode');
In my test website, I added this code through the plugin Code Snippets: https://share.getcloudapp.com/eDulrR6P
After doing this, you may use the shortcode as such anywhere in your website: https://share.getcloudapp.com/kpu4lbkA
Also see: https://share.getcloudapp.com/d5uNDEld
As shown above, you may hook on to the “shortcode hook” by choosing Element type: Hook, and Hook name: Custom hook.
Here is a screenshot of it working when logged-in as administrator: https://share.getcloudapp.com/JruGe6zl
Logged-out: https://share.getcloudapp.com/6quEJe7E
Hope this helps! :)
Fernando,
Thank you for that detailed example. Much appreciated.
Question: in the code it says author. Would this refer to the logged in user being the creator/author of the post or to the role author? The role author won't work. I need to make it the creator of the post as the only one to see it.
Thanks again.
Laura
Hi there,
that Display Rule of Author will simply display the Element to any user that is logged in with the Author role, it won't handle displaying it just to the current post author.
Try this snippet to create the shortcode:
function db_show_only_admin_or_author($atts, $content = null) {
global $current_user;
get_currentuserinfo();
if ( is_user_logged_in() && ( $current_user->ID == $post->post_author || is_admin() ) ) {
ob_start();
do_action('your_hook_name');
return ob_get_clean();
}
}
add_shortcode('author_admin_hook', 'db_show_only_admin_or_author');
Change the your_hook_name to something unique for your need.
This is the shortcode you add to the page or wherever you need it: [author_admin_hook]
Now it will only output the your_hook_name hook if the user us Logged in and is either the current post author or the admin.
Now in your Elements display rules you set the Location to Entire Site.
David,
AWESOME! Thank you so much! I will give it a try.
Woohooo! Thanks.
Laura
You're welcome