I'm trying to figure out how to minify & combine js/css code given this situation:
I'm fairly new to grunt, I've used it in the past with custom web apps, but never with wordpress, I wonder if it can help when you have lots of PHP scripts / pluging which injects their ugly code.
So my question is: is there a way to make grunt work with wordpress so that production code is served in the case above? If so, how?
I'm afraid there's no way to achieve what you're looking for without modifying those plugins.
Grunt is just a JavaScript task runner - it has no sense of a web application, be it WordPress or something custom. You give Grunt some input, and you tell it what to do with that input, and it does it. Therefore, in order to use Grunt to minify and concatenate all of the JavaScript and CSS on your site, you have to extract it from the plugins and place it into an appropriate file structure.
Generally speaking, when a plugin insists on inlining a bunch of JavaScript and/or CSS, it's not a very good plugin. For example, my team uses gulp.js (similar to Grunt) for a lot of WordPress front-end development (concatenation, minification, fingerprinting, automatic prefixes, and so on), and we're very particular about which plugins we use (if any at all) - one of the reasons being exactly what your question is about.
Your plan seems a little messy. In the best case scenario, let's assume that you have configured and used a simple Grunt task in order to minify all your CSS and JS your Wordpress instance uses.
That means that you have to dig through your code, find where each of your plugins fetches styles or scripts , cut them off and minify 'em using Grunt. Afterwards you should take up the final minified file and inject it into your Wordpress instance again.
Besides the fact that you will have to do a lot of custom coding, updating your plugins will give you lots of pain.
In order to stick to a scalable and easy to follow plan I suggest using BWP minify plugin which will take care of your styles and scripts, it provides CDN support.
You may then use Grunt as a code quality check mechanism. Uncss is a great tool helping you find unused styles. Grunt-usemin is an excellent solution too.
At last, as I see that you are willing to move to command line tools I would highly suggest taking a look at WP-CLI it's a wonderful command line interface for Wordpress.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With