Solved: Fonts not displaying, blocked by CORS policy using child theme

Using free Astra theme, created a child theme, text fonts are not displaying correcly any more but are using some browser fallback fonts instead.

CORS error message logged in website console:

Access to font at '*****.com/wp-content/astra-local-fonts/julius-sans-one/1Pt2g8TAX_SGgBGUi0tGOYEga5WOwnsX.woff2' from origin 'https://*****.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Website console logged CORS error: Access to font at from origin has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

What is CORS?

Cors is short for Cross-Origin Resource Sharing (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)

CORS definition: Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. This means that a web application (like WordPress) can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.

The reason that fonts are not displaying after creating a child theme for Astra is that loading fonts in CSS via @font-face is also affected by CORS policy https://www.w3.org/TR/css-fonts-3/#font-fetching-requirements

More specifically from the Mozilla article:

w3.org, Font fetching requirements

The implications of this for authors are that fonts will typically not be loaded cross-origin unless authors specifically takes steps to permit cross-origin loads. Sites can explicitly allow cross-site loading of font data using the Access-Control-Allow-Origin HTTP header. For other schemes, no explicit mechanism to allow cross-origin loading, beyond what is permitted by the potentially CORS-enabled fetch method, is defined or required.

To solve add this code to your website’s .htaccess file

# fix CORS error for Astra child theme

<FilesMatch ".(eot|otf|ttf|woff|woff2)">
    Header always set Access-Control-Allow-Origin "*"
</FilesMatch>

Reload page and you should see the CORS error gone from your website’s console.

Hope this helps someone. Feel free to leave a comment if you have a better solution or you see error in my solution. I was able to get the website fonts loading correctly using the above solution.

Post Author: Tom Pai