Home Forums Gutenberg Check if Innerblocks is empty


Check if Innerblocks is empty

  • Is there any way to wrap <InnerBlocks> in a conditional statement to see if it’s empty or not?
    I have an ACF block with innerblocks, much similiar to how the core Cover block works. Sometimes innerblocks is not needed, but since I provide a template the markup outputs even if the blocks are empty.

    Of course I (the client) can remove the blocks from admin and so on but it would be a nice solution if we can check for empty if someone forgets to remove them.

    $template = array(
    array('core/heading', array(
    'level' => 2,
    'placeholder' => 'Title',
    array('core/paragraph', array(
    'placeholder' => 'Content',
    ) )
    <InnerBlocks template="<?php echo esc_attr( wp_json_encode( $template ) ); ?>" />

  • Just wanted to bump this, as I have the same issue. Empty core blocks still generate their html markup on the front end even if the core fields are empty and there does not seem any way to check for this?

  • Ok so after some digging I’m not sure if this is an ACF or Gutenberg issue. I decided to try and check if a core/heading or core/paragraph have any content in them. My code is more for debugging at the moment.

    I have used pretty much the same code as the OP in my block markup.

    	global $post;
    	// Get all blocks on the page.
    	$blocks = parse_blocks( $post->post_content );
    	// Loop over the blocks.
    	foreach ( $blocks as $block ) {
    		// Check for the accordion block.
    		if ( $block['blockName'] === 'acf/accordion' ) {
    			// Check if any inner blocks are used. There is an empty core heading and core/paragraph block.
    			if ( $block['innerBlocks'] ) {
    				$block_innerBlocks = $block['innerBlocks'];
    				foreach ( $block_innerBlocks as $inner_block ) {
    					// Check for the core heading block.
    					if ( $inner_block['blockName'] === 'core/heading' ) {
    						// This is where things get messy! We need to check if the core block has any content but its outputting the html element markup even if nothing has been entered.

    So if you check the var_dump you will notice that even if a core block has no content entered it will still output the actual <h2…. markup as a string.

    Dumping just $inner_block I can’t see that there anything that can actually be used to conditionally check if content is in there or not?

    I could go down the route of checking the string length of $inner_block[‘innerHTML’] or $inner_block[‘innerContent’] but thats a flawed idea as class names could change and the string length value will change.

    Anybody got any suggestions?

  • It says solving here, so when might we expect a fix to this?


Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.