1

I am trying to avoid inline CSS and move the custom CSS to the head of HTML document.

Found this article https://www.cssigniter.com/late-enqueue-inline-css-wordpress/ and tried to implement this solution for shortcode, but have problem to get global variable $custom_css that is set in div_shortcode to my_custom_css function ( value is empty, but should be, for example: .my-div {color: red;} )?

Shortcode usage:

[div style="color: red"]Example[/div]

PHP Code:

$custom_css = '';
function div_shortcode($attr, $content = null) {
extract(shortcode_atts(array('style' => ''), $attr));
    $output = '<div class="my-div">';
    $output .= do_shortcode($content);
    $output .= '</div>';
    global $custom_css;
    $custom_css = '.my-div {'.$style.'}';
    return $output;
}

function my_custom_css(){
    global $custom_css;
    wp_register_style( 'my-custom-css', false );
    wp_enqueue_style( 'my-custom-css' );
    wp_add_inline_style( 'my-custom-css', $custom_css );
}

add_shortcode('div', 'div_shortcode');
add_action( 'wp_head', 'my_custom_css' );

The result I want is to get in the head of HTML:

<style id='my-custom-css-inline-css' type='text/css'>
.my-div {color: red;}
</style>

and in the output of post content:

<div class="my-div">Example</div>
  • 1
    Where do you intend to place the shortcode? Shortcodes are typically for the post editor. If you want to inject CSS into the head, you can user the header.php file (although I don't recommend it). You should look at wp_enqueue_scripts – Tim Hallman Dec 6 '17 at 17:10
  • In the example above it is just regular shortcode code for text editor. – WPuser Dec 6 '17 at 17:12
  • 2
    Shortcodes are run inside the_content so they are after the head has been output. You would probably be better off to add the CSS to your style.css (if using a child theme) or in the Customizer - either of those methods will put your CSS in the <head>. Then, have your shortcode just output the class - though it may be just as easy to type in <div class="red-div"> as it is to type [div style="color: red']. Or perhaps I am misunderstanding and you are wanting to add arbitrary CSS rules rather than a set of fixed styles? – WebElaine Dec 6 '17 at 20:57
  • I am developing theme and trying to avoid inline CSS when user is using parameters for changing colors. There seeems to be a solution to render CSS in head based on dynamic shortcode parameters, please have a look here cssigniter.com/late-enqueue-inline-css-wordpress I am trying to use this solution, but need help to implement it for shortcode. – WPuser Dec 6 '17 at 23:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.