Absolute / domain-relative path for asset URLs in CSS

Alright, the underlying issue is the fact that currently remotely added editor styles (fetched by URI) don’t get a baseURL field when being used in the Gutenberg Block Editor. The missing baseURL field prevents the Gutenberg editor post-processing from rewriting those stylesheet-relative URLs, resulting in broken styles.

Relevant WordPress trac ticket:
https://core.trac.wordpress.org/ticket/55728#ticket

The editor styles can be added as files by path relative to theme directory, so the styles are not remotely fetched and the baseURL field is added:

<?php
namespace App;
use function Roots\asset;
use Webmozart\PathUtil\Path; // library is used
add_action('after_setup_theme', function () {
    add_theme_support('editor-styles');
    // Add frontend styles as editor styles
    // Must be added by relative path (not remote URI)
    // (@see https://core.trac.wordpress.org/ticket/55728#ticket)
    $absCssPath = asset('app.css')->path();
    $absTemplatePath = get_template_directory();
    // path to editor styles file must be relative to the theme directory
    $relCssPath = Path::makeRelative($absCssPath, $absTemplatePath);
    add_editor_style($relCssPath);
});

1 Like