Dynamic Styles in gutenberg editor a requirement of themeforest for gutenberg optimized themes

Gutenberg Optimized Definition

Themes with the Gutenberg Optimised attribute turned on, or otherwise advertising themselves as optimized for Gutenberg, must do the following as a minimum:

  • Make sure that the Gutenberg editor is styled to match the frontend output as closely as possible. This should include any fonts used and any dynamic styles coming from settings etc. More information.
  • Change the editor widths to match the widths used in the theme as closely as possible. More information.

the above text is stated as a requirement by themeforest if a theme want to advertise itself as gutenberg optimized. now my question here is about dynamic styles, its not supported in wordpress to add dynamic styles to the editor as stated in this issue raised on GitHub https://github.com/WordPress/gutenberg/issues/18571 as add_editor_style() function only takes path to css files and if you want to add dynamic styles to the editor you need to hook into enqueue_block_assets or enqueue_block_editor_assets hooks but as those hooks are built for styling your own custom blocks they don’t have high enough specificity for your styles to get applied to gutenberg builtin blocks. so my question is if something is not supported by WordPress itself how its stated as a requirement in themeforest? or am i missing something there ? because i have tried the hooks enqueue_block_assets or enqueue_block_editor_assets, they gets enqueued in the editor but they don’t have that much high level of specificity to get applied to Gutenberg builtin blocks even with the !important flag or property

1 Like

if anyone is having the same problem then the work around towards enqueueing dynamic stylesheet is to enqueue an empty css file and hook into the enqueue_block_editor_assets or enqueue_editor_assets hook depending on your situation and then add the function wp_add_inline_style() which will take your dynamic styling into the editor like so

function _themename_enqueue_block_editor_assets(){

    $url    =   get_theme_file_uri();

    $ver    =   _themename_DEV_MODE ? time() : false;

    wp_register_style( '_themename-editor-enqueue-stylesheet',$url . '/dist/assets/css/editor-enqueue.css', array(), $ver, 'all'  );

    wp_enqueue_style( '_themename-editor-enqueue-stylesheet' );

    $primary_color = sanitize_hex_color( get_theme_mod( $value, '#1976d2' ) );

    $inline_editor_css = "

    .tag-cloud-link { 

        background-color: {$primary_color};

    }

    ";

    wp_add_inline_style( '_themename-editor-enqueue-stylesheet', $inline_editor_css );

}

add_action( 'enqueue_block_editor_assets','_themename_enqueue_block_editor_assets' );

while adding your regular block styles that are not dynamic to the block editor with the add_editor_style();

1 Like