Logged in/out condition in Gutenberg

When creating the SnippetClub website, I wanted a way to hide or show blocks depending on certain conditions. Now there are plugins that do this already, however with a few lines of code, you can start creating your own conditions.

The condition we are looking at today is if a user is logged in or logged out.

1. Go to the page you want to add your conditions to

Go to the page you want to add your conditions to

2. Select the block you want to apply the logged in condition to

Select the block you want to apply the logged in condition to

3. Logged in Block

Under the advanced tab in the sidebar, add the class “logged-in” to your block

screenshot 2022 09 25 at 15.43.57

4. Logged out Block

Repeat steps 2 and 3 for the logged out block with the class “logged-out”

screenshot 2022 09 25 at 15.41.06

5. Save your post

Save your post

6. Add the code

Copy and paste the code below into your functions.php or snippet plugin. I am using WPCodebox.

php
/* * tct_render_block * * @function Show or hide blocks based on conditions * @author Taylor Drayson * @since 25/09/2022 */ function tct_render_block( $block_content, $block ) { switch($block['attrs']['className']){ case 'logged-in': return is_user_logged_in() ? $block_content : ''; case 'logged-out': return !is_user_logged_in() ? $block_content : ''; } return $block_content; } add_filter( 'render_block', 'tct_render_block', 10, 2 );

7. Save your code

Save your code

8. Final outcome

Once you have added the classes and the code to your website. You should now see that the blocks only show depending on it if you are logged in or logged out.

Logged in view

screenshot 2022 09 25 at 15.32.18

Logged out view

screenshot 2022 09 25 at 15.34.02

👋🏻 Weekly Tutorial Digest

I send out a weekly newsletter with links to new tutorials written in the last week, you can subscribe below.

🔒I won't send you spam, I promise