I have a child-theme -> parent-theme setup, where I need to have stylesheet called generated.css loaded in addition to the style.css file added by the active child-theme. The generated.css file is residing in the parent-theme and is being dynamically generated and provided by the parent-theme..
I started out the obvious way, simply adding an import rule to the beginning of the child-themes style.css:
/* Get Parent BASE CSS */
@import url('../parent-theme/style.css');
/* Get Parent GENERATED CSS */
@import url('../parent-theme/generated.css');
But this does not work for two reasons.
1) I want to be able to add a cache-busting version number to the file:
<link rel='stylesheet' href='http://www.com/wp-content/themes/parent-theme/generated.css?ver=2389642855'>
2) I want the file to be loaded last, after the child themes style.css
Is it possible to hook in the loading of this generated.css stylesheet into the head so it is added after the child-theme’s style.css using the functions.php of the parent theme?
What hook or WP mechanism could I use?
Absolutely!
Into functions.php, like you said. I’ll call it cache_busting_styles because I like how it sounds.
First, you set up the style via wp_enqueue_style, then call it during the action hook wp_print_styles, Also, you’ll want to set up a variable and pass it in there as the version number as well:
wp_enqueue_style accepts 5 arguments, first the handle, an ID wordpress associates with the stylesheet (must be unique), second the URL of the file, third the other files it depends on (any required files that should be loaded along with this file, I left it null, you may add anything you want, it uses other enqueued stylesheets handles), fourth the version, which it adds to the end of the link URL just like what you are looking for (You may pass whatever you want into this, WordPress puts it’s current version in here by default), and finally the media argument for the CSS file (screen, print, all, etc…) I hope this helps!
Edit: Just wanted to make clear that using this method should always add this sheet after the default style-sheet, but to make very sure, add_action accepts a third argument which is the priority of the action. A very large number will guarantee it running last, but something like 8 or 12 should do the trick, just in case you need to force the order.
you can simply enqueue the generated.css style. Use the following code in your child themes function.php file