Most WordPress front-end developers add custom code to a Site by using a functions.php file or a plugin. My personal choice is to use a functions.php file and, once you get the hang of it, it’s an incredibly powerful and effective file once scripts/code are added.
WordPress IF conditions in functions.php
The issue many front-end developers encounter is the balance between code efficiency and effectiveness. A good example of this is when a certain bit of code needs to be run on a single page only; if the code is included in functions.php or a plugin then the code will run whether the page the code applies to ins opened or not. Let’s say you have a website with 10,000 daily page views and no caching and the page requiring the code is only viewed twice per day; the code added to the plugin or functions.php will be run 9,998 times per day when it really didn’t need to be run at all. Even if we add a PHP if construct to the script/code to run only when the page is loaded we still need to run the condition which is a bit of code in itself.
To keep the code as efficient as possible we really want to only run code when necessary.
How to run code on a WordPress page without using a condition
If you use a Genesis framework Theme by StudioPress you’re in luck. Genesis included a section for custom scripts in the Post or Page edit screen. What this does is run the code or script in the ‘Script’ field when that specific page or post is opened. The advantage of using this field over adding a conditional statement to functions.php or a Plugin if, of course, that the script is only executed when needed and no conditional statements needed to be added elsewhere that use resources unnecessarily.
An example using the Genesis ‘Scripts’ field
As a simple but easy to see example, I’ve added the scripts for four Google Fonts to the Genesis Scripts field for this blog post. The fonts are therefore only loaded when this post is viewed.
A simple and very efficient means of adding custom code or scripts to a simple WordPress Page or Post.