Enqueue inline styles

Sometimes you’ll need to dynamically generate CSS. This could be a logo upload field (as shown in the example), changes to a color scheme, or styles that run only on certain pages.

Instead of manually echo’ing inline styles, use the wp_add_inline_style() function. This allows you to define CSS, then attach it to a specific stylesheet. Whenever that stylesheet is enqueued, your inline styles appear as well. If you attach them to the child theme’s stylesheet your styles will appear sitewide. If you attach it to a specific stylesheet that only loads on some pages, your styles will only appear on those pages as well.

More information in the Codex.

* Enqueue Inline Styles
* @author Bill Erickson
* @link http://www.billerickson.net/code/enqueue-inline-styles/
function be_enqueue_inline_styles() {
$css = '';
$logo = get_option( 'options_be_site_logo' );
if( $logo ) {
$logo = wp_get_attachment_image_src( $logo, 'full' );
$css .= '
.site-title { background-image: url(' . $logo[0] . ');}
if( !empty( $css ) )
wp_add_inline_style( 'child-theme', $css );
add_action( 'wp_enqueue_scripts', 'be_enqueue_inline_styles' );
view raw functions.php hosted with ❤ by GitHub

Bill Erickson

Bill Erickson is the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk