With HTML5 it’s possible to declare CSS stylesheet inside the body tag. This gives WordPress developers a better solution for including CSS on the fly, such as via a shortcode. It instantly makes several workarounds redundant. The native WordPress function wp_enqueue_style can now be called mid-page, which will print a stylesheet in the footer. Two disadvantages arise from this method and here is an alternative solution that solves it.
In part 1 we learned that
elements inside the body tag don’t validate at the moment. While browsers handle them just fine, it’s always nice to pass validation without errors. An alternative to this was to alter the output and use the style tag with the new scoped attribute instead. Then, the code will show up valid like:
@import url(stylesheet.css);
The second disadvantage is that our CSS now loads at the end of the page, after the content we want to style. This may cause some styling issues during pageload. Since we can load the CSS anywhere inside the body tag, there is no real reason why it needs to be printed in the footer. If we do that, we also limit the styling issues on pageload.
We can write a function that prints the stylesheet declaration immediately. Let’s say you have a shortcode that inserts a slider, your shortcode would include a special function that prints the CSS before the rest of the slider output. The easy way would be simply to write a function that outputs the required html directly and this is what many developers tend to do. WordPress has specific ways of dealing with styles and scripts to help reduce conflicts and redundancies, so it is important we take advantage of that. So what we are going to do is tap into the API WordPress uses.
The first step is to register your CSS stylesheet with wp_register_style by wrapping it into a function and loading it into the wp_enqueue_scripts hook. Here is an example where we are including the Media Element Player.
function register_mediaelementjs() { wp_register_script( ‘mediaelementjs’, get_bloginfo(‘template_url’).’/inc/mediaelementjs/mediaelement-and-player.js’, array(‘jquery’), ‘2.6.3’, true ); wp_register_style( ‘mediaelementjs’, get_bloginfo(‘template_url’).’/inc/mediaelementjs/mediaelementplayer.css’ ); }
add_action( ‘wp_enqueue_scripts’ , ‘register_mediaelementjs’ );