TransWikia.com

Use wp_add_inline_style to add code to before wp_head?

WordPress Development Asked on October 30, 2021

I’m building a WordPress theme for Themeforest. In the customizer I’ve given users the ability to also use the rem unit for their font sizes. I’ve created three different settings that control the font-size on the html or :root element for three different media queries.

When I add the code for the :root or html in (1) a stylesheet or (2) wp_add_inline_style, the computing of the styles via the Browser takes too much time. The browser first renders all the text as if the rem size is 16px and after a second all the fonts scale to the correct size. This looks terrible. I only encountered this on Safari on iOS. (Is this a common problem? I can’t find other people experiencing this on the internet…)

The only solution to this problem is when I manually add a tag before the wp_head() action. In this way, the styles are loaded so early that the browser does compute them correctly. Adding the CSS in this location greatly improves the user experience.

Themeforest has the requirement that inline css is not allowed, except for background-images. Wp_add_inline_style is allowed. Is it possible to add a <style> tag in such a way to the <head> with wp_add_inline_style, that it is the first element before wp_head or the first element in wp_head?

Thanks!

One Answer

Yes, that should be doable. Just enqueue your inline styles with callback hooked to wp_enqueue_scripts and priority set to 0 (assuming other styles are loader later / lower priority / bigger number). You also need to register a dummy handle to which you attach the inline styles to, so no other styles are loaded before them.

function my_pre_theme_assets() {
    wp_register_style( 'dummy-handle', false );
    wp_enqueue_style( 'dummy-handle' );
    wp_add_inline_style( 'dummy-handle', '* { color: red; }' );
}
add_action( 'wp_enqueue_scripts', 'my_pre_theme_assets', 0 );

Dummy handle idea seen here, wp_add_inline_script without dependency

Answered by Antti Koskinen on October 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP