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.
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.