Adding Dynamic and Piggyback Styling in WordPress

Often, when creating a WordPress theme, some of the theme’s styling will need to be dynamic because it is based on user selections stored in the database. WordPress provides a function called wp_add_inline_style() which allows for inline styles to be loaded after a specific CSS file.

For example:

add_action( 'wp_enqueue_scripts', function () {

wp_enqueue_style( 'custom-style', get_stylesheet_directory_uri() . '/css/custom.css' );

$color = get_theme_mod( 'custom-color', '#FE001A' );
$custom_css = ".has-background-color{background-color: $color;}";

// Loads inline styling, but only after 'custom-style' is enqueued.
wp_add_inline_style( 'custom-style', $custom_css );

} );

Note: If ‘custom-style’ above is dequeued, then the inline styling will not be added to the page.

Aside from being an easy way to add dynamic styling, this function is especially useful if you are extending a theme or plugin and need to add a few extra styles which don’t really call for loading an entire CSS file.

If you are wondering if there is a wp_add_inline_script() function which will do the same thing for scripts that wp_add_inline_style() does for styles, that doesn’t exist yet but is something that should eventually make its way into WordPress core.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.