WordPress: stylesheet inclusion order

In WordPress, custom style and script resources should be incorporated with the corresponding API calls, such as wp_register_style and wp_enqueue_style. These API calls are usually only indirectly called: they should be registered with the add_action API call, which supports priorities. WordPress then calls the wp_register/enqueue_* functions automatically at the right time. The order of these calls is given by the priorities set up when calling add_action. A big warning: these priorities, however, do not translate into the order in which the script/style resources end up in the HTML. This has been clarified in this StackOverflow answer: http://wordpress.stackexchange.com/a/91964

Stylesheet ordering can only reliably be achieved with WordPress’ concept of “stylesheet dependencies”. These can be defined with the fourth argument to wp_register_style, e.g.:

wp_register_style('magnific_popup_style', get_stylesheet_directory_uri().'/magnific-popup/magnific-popup.css', array('twentytwelve-style'));

The fourth argument in this call is array('twentytwelve-style'). This would make sure that the /magnific-popup/magnific-popup.css inclusion (via HTML link tag) is done after inclusion of the stylesheet with the internal handle name 'twentytwelve-style' (as you can see, you need to know the handle name of a stylesheet in order to define it as a dependency).

Application scenario: the 'twentytwelve-style' is the theme’s main stylesheet in my case. Without explicitly defining this dependency above, my WordPress would incorporate the magnific-popup CSS before incorporating my theme’s CSS. However, I need the magnific-popup CSS to override some CSS rules defined in my theme’s CSS. Likewise, I need to reliably make sure that the magnific-popup CSS is loaded after the theme’s CSS. Therefore the dependency.

This is quite a simple concept — it’s just that the WordPress docs are not so explicit about all this. The most complicated thing in all this was to find out the internal stylesheet handle name of my theme (these are the little quirks people hate WordPress for). I’ve written another small post about how to reliably find out this one: see WordPress: theme stylesheet handle name

Leave a Reply

Your email address will not be published. Required fields are marked *

Human? Please fill this out: * Time limit is exhausted. Please reload CAPTCHA.