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.

<?php
/**
* 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

css customizer enqueue inline

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

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

Let's Talk