Ph: 0800 4 WPNET | Contact
Ph: 0800 4 WP NET | My WP NET | Contact

WordPress Tip: Enqueuing Inline CSS

WordPress Tip: Enqueuing Inline CSS
July 1, 2014 GB

We’ve been working with WordPress for years, but there are still some gems to be discovered within the WordPress Codex. This beauty has been around since version 3.3, but I was not familiar with it until very recently.

Ever needed to include a variable, inline style for your plugin or theme? Enqueueing external CSS files with WordPress’ wp_enqueue_style() function (and its companions) is pretty good but it lacks the functionality to include inline CSS styles. Or does it?

wp_add_inline_style allows you to print extra styling whenever a certain style-sheet is loaded. For instance suppose a plug-in or theme makes use of the class .mycolor in a style-sheet to set a background color. This can be over-ridden by a user chosen color, stored in the database by using wp_add_inline_style to print the extra styling.

<?php
function my_styles_method() {
	wp_enqueue_style(
		'custom-style',
		get_template_directory_uri() . '/css/custom_script.css'
	);
        $color = get_theme_mod( 'my-custom-color' ); //E.g. #FF0000
        $custom_css = "
                .mycolor{
                        background: {$color};
                }";
        wp_add_inline_style( 'custom-style', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'my_styles_method' );
?>

Read all about this function in the Codex.