Search code examples
wordpressvue.jswordpress-rest-apiwordpress-gutenberg

How can I include the CSS rules from classes added to blocks in the Gutenberg editor using the REST API?


I'm working on a decoupled Vue.js/Wordpress application, and I would like to render out some blocks as HTML with the same styling applied in the editor. I'm requesting the page via the REST API and simply displaying the rendered content. I'd like the styles associated with the Gutenberg classes that are added when a user modifies a block in the editor to apply in my Vue app.

I'm currently importing the following into my project but these don't seem to cover styles modified in the editor:

@wordpress/block-library/build-style/common.css @wordpress/block-library/build-style/style.css @wordpress/block-library/build-style/theme.css

An example class with missing style could be .has-vivid-green-cyan-color when changing the text colour within a block. I'm not necessarily picky about how this included in the Vue app. It'd just be massively helpful to have it at all!


Solution

  • The CSS styles are generated by PHP from the theme.json if the block supports the global styles UI editor. The core wp-includes/script-loader renders the "missing" styles inline in the <head>, so if you access the content headless or another way, you won't get the inline styles created in the Editor.

    You could use the core PHP function wp_get_global_stylesheet() / wp_get_global_styles_custom_css() (version 6.2+) to create a custom REST endpoint for your project to get the "missing" styles into your project, eg:

    PHP

    /**
     * Get stylesheet callback function
     */
     public static function get_stylesheet_css( WP_REST_Request $request ) {
        // Options include: 'variables', 'presets', 'styles', 'base-layout-styles'
        // Returns empty string if invalid option given
        $option = $request->get_param( 'option' );
        
        return wp_get_global_stylesheet( array( $option ) );
    }
    
    /**
     * Register new REST route
     */
    add_action( 'rest_api_init', function () {
      register_rest_route( 'theme-css/v1', '/(?P<option>\w+)', array(
        'methods' => 'GET',
        'callback' => 'get_stylesheet_css',
      ) );
    } );
    

    To get the missing styles, you can then access them via [example.com]/wp-json/theme-css/v1/variables which contains the definitions of the preset colors.