I've been reviewing tutorials on creating blocks for Gutenberg but I am unclear how to handle a particular use case - conditional blocks.

I am looking at creating a custom post type for which I will register my own block type. These blocks will only be displayed if certain conditions are true. These conditions will be either boolean flags or integer comparisons (the values coming from wither custom user variables (meta) or session values).

If all conditions are true the block should be rendered but if one or more are false then (obviously) nothing is shown.

I cannot quite get my head around where I would place the logic for this. Admittedly my grasp of this new Gutenberg system is a bit shaky which is probably why I need some assistance.

For example:

<p logic="IF(is_logged_in,SHOW,HIDE)">My wonderful secret bit just for members.</p>
  • Do you mean a block which is already in the post content, or instead in the appender list, or a block which is part of the page template? If you could give the exact case it might be easier to figure out a solution. – Alvaro Nov 30 '18 at 16:08
  • Just a block which is part of the post content. For example IF (SomeCondition!=TRUE): Don't show this paragraph. – Matthew Brown aka Lord Matt Dec 7 '18 at 4:35
  • 2
    Maybe this approach can help? – birgire Jun 10 '19 at 11:25
  • 1
    I think that will do nicely. – Matthew Brown aka Lord Matt Jun 10 '19 at 11:36
  • You can also nest blocks ( make the child blocks loaded only within the parent, creating a condition ), have a look at the columns & column blocks in core for more info. The ALLOWED_BLOCKS constant can be used to control which blocks are allowed to be used inside of a block – admcfajn Jul 21 '19 at 18:19

In the edit method for your custom block, when rendering the components you can use the "conditional + &&" pattern:

    <PanelBody title={ __( 'My Panel' ) } >

        { myCustomBool &&
                onChange={ value => {
                } }
        { 'marmots' !== myCustomThing &&
                onChange={ value => {
                } }


In the above example, the conditionals just before the "&&" will determine whether the component that follows will be rendered.

This is sometimes referred to as a "short circuit conditional".

| improve this answer | |

If you want to give the editor control over what blocks are displayed to logged in users or not you could use this plugin: https://wordpress.org/plugins/block-options/

Then you do not need to code it into your block as every block will have the option of being only for your members or not.

| improve this answer | |
  • That's nice, for those that this is all they want. I am specifically looking for ways to create conditional logic. – Matthew Brown aka Lord Matt Jul 4 '19 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.