WordPress Block Editor Gutenberg running code inside ! is_admin()

It appears this is a known issue with the block editor (aka Gutenberg).

That Trac ticket suggests a workaround, too: replace your

if ( ! is_admin() ) { ... }

with something like this:

global $current_screen;
if ( 
    ( ! is_admin() ) && 
    ( ! 
        ( 
            // Checks the value of WP_Screen::is_block_editor().
            $current_screen instanceof \WP_Screen && 
            $current_screen->is_block_editor()
        )
    )
   ) { ... }

This code is untested. I’m pretty sure I matched the ( and ) but make sure it works as expected before you put it in production.

If you’re doing this in a lot of locations (ie, > 1), I’d suggest creating a helper function even closer to the code suggested in the Trac ticket’s comments:

function wpse416155_is_admin() {
    if ( is_admin() ) {
        return true;
    }
    global $current_screen;
    if ( $current_screen instanceof \WP_Screen &&
         $current_screen->is_block_editor() ) {
        return true;
    }
    return false;
}

// ...
// ...
// ...

if ( ! wpse416155_is_admin() ) {
    // ...your non-admin code here...
}