If you’ve ever had to add some JavaScript to your self-hosted WordPress site, but you don’t really know the first thing about PHP code, this post is for you!

Time and time again, I see the same bad advice for adding a snippet of JavaScript to your theme. Here’s a real excerpt:

To add the [script] to your self-hosted WordPress page, go to your dashboard and select Appearance and then Editor. From there, you can view your Templates, followed by php files. Select the “footer.php”, scroll down to the closing body tag, and place the [script] directly above it.

Don’t do that.

First of all, don’t edit those files in the WordPress Editor at all if you can avoid it. It’s quite possible that you could make an accident in a PHP file, save it, and get completely locked out of your site (yep, I’ve done it in years past). If you’re ready to edit code, you should get yourself a real live code editor and learn how to update such things properly.

But, more often than not, you don’t need to learn PHP to include some JavaScript in the footer. Do yourself a favor and grab the Insert Headers and Footers plugin and just plug what you need in there. It’s coded well, and hooks into the appropriate “action” called wp_footer().

If adding your code there doesn’t work—meaning the code literally doesn’t end up loading on the front-end of your website—you may have an issue with your theme. Quickly switch to a default WordPress theme (Twenty Fourteen, Twenty Thirteen, etc.). If it works on that theme, your theme is poorly coded. Make plans to fix that with a higher quality theme, or go ask that developer you hired why they didn’t follow WordPress’s best practices. Lacking the wp_footer() (and, potentially, other) “actions” means that plugins will work unpredictably with your site, and you’re missing out on the value of the WordPress ecosystem.

If you feel the need to add a code snippet somewhere instead of using that dead simple plugin above, please properly create your own plugin, and enqueue your scripts.

Why the fuss?

This is one of those places where you need to trust folks who have been where you are. If you want your snippet of code to carry over when you change themes, there’s no reason to hardcode things into your theme files—that’s what plugins are for.

Save yourself the trouble of having to fix it later or not knowing why things aren’t working right. Use a good plugin (or correctly build your own), and let that vet that theme you’re using.

Want blog posts sent directly to your email?

Sign up to get emails from Logos Creative! You'll get the latest blog posts and an occasional extra email. Unsubscribe (easily) at any time.

December 20, 2013 — 1 Comment — In Blog, Tutorial, WordPress