0

Sometimes you have a theme or a very lightweight WordPress plugin (like a single PHP file) and you want to add some CSS easily without having to load more files or folders, etc.

How can you add some basic inline CSS rules using an existing script in WordPress?

1 Answer 1

0

The easiest way to do this is using wp_add_inline_style ... here is the documentation.

A great example I found on a public Gist:

<?php

//Adding CSS inline style to an existing CSS stylesheet
function wpb_add_inline_css() {

        //All the user input CSS settings as set in the plugin settings
        $slicknav_custom_css = "
            @media screen and (max-width: {$ng_slicknav_width}px) {
                {$ng_slicknav_menu} {
                  display: none;
               }
               .slicknav_menu {
                  display: block;
                  background: {$ng_slicknav_background};
               }
               .slicknav_btn {
                  background-color:{$ng_slicknav_button};
                  float:{$ng_slicknav_button_position};
               }
           }";

  //Add the above custom CSS via wp_add_inline_style
  wp_add_inline_style( 'slicknavcss', $slicknav_custom_css ); //Pass the variable into the main style sheet ID

}
add_action( 'wp_enqueue_scripts', 'wpb_add_inline_css' ); //Enqueue the CSS style

And if your plugin doesn't have an existing stylesheet, you can register a "dummy" one like this:

wp_register_style( 'dummy-handle', false );
wp_enqueue_style( 'dummy-handle' );

wp_add_inline_style( 'dummy-handle', '* { color: red; }' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.