WordPress Plugin or Custom Template?

I was playing around with WordPress, trying to create some custom functionality on a page and I quickly ran into a quandary. When do you put code in a plugin and when do you put it in your theme/child theme? It turns out the answer is not what you think, or at least what I thought.

My original thought was, let’s try to keep as much custom functionality out of my theme. That way, if I decide at some point to change themes, that transition will go much smoother without the theme dependencies. However, that independence comes with a serious cost.

In my case I had a bunch of server code that I wanted to call via AJAX. I also had some JavaScript that issued those AJAX calls. I figured it would be good practice to bundle the whole thing up into a plugin. The php code in the plugin was ensuring the JS was in the page by calling wp_enqueue_script(). Unfortunately, what I didn’t realize (I’m pretty new to WordPress here, so forgive me), is that my JS is then going to be included on every single page served up by my site, not just the ones I want.

Unfortunately, there’s no easy way that I could find to say enqueue this script, but just for these pages. Correction. There is way, through theme templates. Just create a custom template, call wp_enqueue_script() from that page, and then wherever you want that functionality, just set the page’s template to your custom template.

Unfortunately, now my code is tied to my theme, which I really don’t like. Anyone have any suggestions?

Update: I figured this out.  Originally I was calling wp_enqueue_scripts directly from my plugin’s __construct().  Instead, now I added an action to call my add_scripts() function on the action wp_print_scripts.  In my add_scripts() function I can then test various conditionals such is_page(‘my-page’).  Using this technique I can ensure that my scripts only get included where I want.

Tagged , , . Bookmark the permalink.

Leave a Reply

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