Gutenberg needs no introduction for serious WP heads these days, and I expect – like me, you’ve all been experimenting with creating funky custom blocks.

During one of these experiments I had created a dynamic block and used a render callback to display the php. This presented a problem, the callback would also attempt to display the block (a complicated carousel) in the post edit screen as well.

The block doesn’t have any options it just pumps out the code to display the carousel, which devoid of any scripts looks like a complete mess on the post edit screen.

Initially I was looking for an is_admin() type of conditional tag, however after some experimentation I discovered that because Gutenberg uses REST is_admin (& get_current_screen()) do not work!

After much hair pulling and gnashing of teeth I came across this page, which explains the problem and offers a solution:

if($is_gb_editor = \defined( 'REST_REQUEST' ) && REST_REQUEST && ! empty( $_REQUEST['context'] ) && 'edit' === $_REQUEST['context']) { 
    // This will display on the post edit screen
    return '<div class="our-work-block" style="text-align:center; padding: 48px 0; background: #6d7f8d;"><h3 style="font-size: 28px; color: #fff;">Our Work Block</h3></div>';
} else {
    // This will display on the frontend       
}

There it is, you will need the whole ‘if’ statement otherwise it doesn’t work so good!

Leave a Reply

Privacy & more..

Cookie Consent Policy