When creating the snippetclub.com 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
2. 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
4. Logged out Block
Repeat steps 2 and 3 for the logged out block with the class “logged-out”
5. 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 );
Copy
7. 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.