Fixing a WP Plugin: Per-Post CSS and JS
A few weeks ago, I installed the “Per Post CSS and JS” plugin for WordPress. This allows you to add a custom field to your post and include extra .css or .js files to link to that individual page.
I only realized today – while testing something else – that the plugin had been firing off warning messages because of an oversight in the code. Warning messages annoy me, so I decided to fix it up.
Where’s the Error?
The plug-in consists of one file – per-post-css.php.
Towards the end of the function per_post_css_js, the script loops through any retrieved CSS and JS files. During these loops, the link tags are added to the head element of the page.
Here’s the line that deals with CSS stylesheets.
foreach ($array_css as $css){ print("\t<style type=\"text/css\" media=\"screen\"> @import url(". $css ."); </style>\n"); }
Notice anything potentially wrong here? What happens if there are no custom CSS files attached to your page?
Foreach looks for an array ($array_css). If a value is passed to foreach that is not an array, it’ll fire off a warning – and that’s just what it did.
The fix is simple enough. Before attempting to iterate the loop, first check to see that $array_css (and later $array_js) is in fact an array.
if (is_array($array_css)) { foreach ($array_css as $css){ print("\t<style type=\"text/css\" media=\"screen\"> @import url(". $css ."); </style>\n"); } }
It’s a minor problem that creates some inconsequential warnings… but it annoyed me so I fixed it. If you have display_errors turned off in PHP (which I usually do) you won’t notice the problem either.
Per Post CSS and JS Updated Source Code
In the plug-in file, the homepage is listed as http://www.flog.co.nz. Oddly enough, I didn’t see a reference to the script on the page anymore, although the author still updates the page.
When I searched for a new copy of Per Post CSS and JS, I found a listing in a WP Plugin Directory – which pointed to an old post on flog.co.nz. That post and the link to the source code are both dead now. Perhaps they were cleaned up to make room for new content.
Regardless, I’m going to re-post the source code for the Per Post CSS and JS WP Plugin here to keep it available.
Kudos and thanks to the original author, Adam Burmister.
Ka Manker said this on July 22nd, 2011 at 2:53 pm
You made several nice points there. I did a search on the subject matter and found most folks will go along with with your blog.