While WordPress is powerful, there are plenty of under-the-hood features that can help you maximize its efficiency. In fact, overlooking inherent functions such as wp_enqueue could even impact your site’s overall effectiveness.
If you optimize your themes and plugins correctly, you can improve your site’s performance while enhancing user experience. The wp_enqueue function is a great place to start. This simple integration can prevent issues with your theme when used with other WordPress plugins.
In this article, you’ll learn exactly what wp_enqueue is all about, and how it can be used to improve your WordPress projects. Let’s get started!
Introducing WordPress’ Template Structure
Part of WordPress’ power is its ecosystem of hierarchies and hooks. Hierarchies are driven by a set of special file names, while hooks can be referenced anywhere within a theme or plugin’s structure. Both work together to ultimately create a cohesive front end that is flexible and compatible with an unpredictable combination of themes and plugins.
Let’s start with the WordPress template hierarchy. This has an impact on the way themes are loaded. Whether you are writing a theme or a plugin, it is important to understand how any front-end loading scripts will be incorporated into the hierarchy.
A primary aspect to understand is that each individual page template gets wrapped around the header.php and footer.php files. With few customized exceptions, both of these files will be loaded no matter what individual page templates get sandwiched between. For example, the home page is loaded like this:
- header.php
- home.php
- footer.php
While an individual post will load these files:
- header.php
- single.php
- footer.php
This way, the top containers with the logo and menu (as well as the bottom containers with any additional footer information) get repeated consistently for every page. This ensures your WordPress page will be correctly, and fully loaded.
Bringing all of this together are WordPress hooks. There are two important functions that get loaded, one into header.php and the other into footer.php. The wp_head() function must be present in header.php:
While the wp_footer() function must be present in footer.php:
They both look for any registered hooks within your plugins and themes. If something needs to be loaded in the header of a page, it gets pulled (or hooked) in by wp_head(), and likewise for the footer by wp_footer().
In other words, you can hook into either of these functions to enable specific unique code to show up on the correct pages of a WordPress website. This is important to understand because WordPress is designed for every single CSS and JavaScript file to be loaded into the theme using these hooks.
While hooks are important for understanding wp_enqueue, they are also the secret ingredient for becoming a power WordPress developer. It’s well worth learning more about how they work and where you can use them.
How wp_enqueue Works
The wp_enqueue() function is a hook in and of itself, which then hooks into wp_head() and wp_footer() as needed. Here’s how it all comes together:
- You write a function which registers your scripts using the correct wp_enqueue script.
- You hook your function into the wp_enqueue_scripts hook.
- These hooks all communicate together so that when wp_head() loads on the front end, your script is found and loaded with the others in the exact correct place.
Neglecting this process means that any theme or plugin that consolidates or reviews scripts will break because yours isn’t loaded using the expected WordPress method. We’ll talk a bit more about that in the next section.
Why Every Single Style and Script Must Be Enqueued
Once you understand how WordPress templates are loaded, you see get why it’s so important you load every single style and script this way. If you don’t, WordPress has no idea your file exists. This is WordPress’ way of keeping track of everything that’s going on within a website.
Consequently, it’s impossible to properly optimize the performance of a WordPress site if even one script is missing. Enqueuing loads your script into the system. This way, WordPress can always replicate it at the correct spot in wp_head or wp_footer regardless of any theme customizations.
Many plugins use the same scripts, but enqueuing enables them to share files rather than attempting to load them multiple times or creating version conflicts. Any optimization plugin or plugins that rely on similar or competing script libraries need to be able to detect these types of issues so they can be debugged and resolved without needing to hack your code. Ultimately, enqueueing scripts ensures greater compatibility across multiple plugins and themes.
How to Use wp_enqueue In Your WordPress Project
Before getting started, it’s important to understand that JavaScript and CSS files load differently. This is because they require different HTML tags. You’ll also want to make backups of your code before making any changes to your site.
If you are working on a live site, you’ll need to access your files using File Transfer Protocol (FTP). FileZilla is a great free cross-platform tool for doing this. Without further ado, let’s jump into coding your scripts into WordPress with wp_enqueue!
Load Scripts Using wp_enqueue_script
Loading JavaScript files is possible with the wp_enqueue_script() function. This function can take five arguments, in this order:
- $handle: This is a unique string to name your script, such as my-custom-script, and is required.
- $src: This is an optional string pointing to the full path of your desired file.
- $deps: An optional array of dependencies. If your script requires jQuery or another registered script, you can list all the handles for those required scripts in an array.
- $ver: You can optionally keep track of script versions here using a string for caching purposes.
- $in_footer: This is an optional boolean value that forces the script to load in the footer rather than the header.
To register your scripts, you’ll set up a custom function and use wp_enqueue_script to load each one individually. Here’s an example code snippet you can reference in your own theme or plugin.
function torque_enqueue_javascript() { wp_enqueue_script( 'custom-name', get_template_directory_uri() . '/path/to/script.js' ); }
Once you’ve created this function, you need to use the wp_enqueue_scripts action hook to actually register it into the system. Below your function, you can use the add_action() function to connect with wp_enqueue_scripts.
add_action( 'wp_enqueue_scripts', 'torque_enqueue_javascript' );
Here, the first parameter is the hook name, and the second is that of your custom function. You’ll want to leave the hook name intact and customize the function name to match yours.
Load Stylesheets Using wp_enqueue_style
Loading in CSS files is incredibly similar, but you’ll use a slightly different function within your script’s loading function. You can choose to keep things separate with an entirely new function to load into wp_enqueue_scripts, or add onto your existing scripts function. For the sake of clarity, we’ll show you how it works in a new function.
The wp_enqueue_style() function also accepts five parameters. Here’s the breakdown:
- $handle: This is a unique string to name your CSS file, such as my-custom-styles, and is required.
- $src: This is an optional string pointing to the full path of your desired stylesheet.
- $deps: An optional array of dependencies. If your script requires another CSS file to work, you can list all the handles for those required stylesheets in an array.
- $ver: You can optionally keep track of stylesheet versions here using a string for caching purposes.
- $media: This is an optional string to specify media types. You can use media types like all, print and screen. Media queries such as (orientation: portrait) and (max-width: 640px) will also work.
To register your stylesheets, you can either add to the existing custom function or create a new one. We’ll show you in a new function how to use wp_enqueue_style to load each script individually. Here’s the example code snippet for reference:
function torque_enqueue_stylesheets() { // Load main stylesheet wp_enqueue_style( 'my-theme', get_stylesheet_uri() ); // Load other stylesheets wp_enqueue_style( 'custom-name', get_template_directory_uri() . '/path/to/stylesheet.css' ); }
With this function ready to go, you can use the same process as before to hook it into wp_enqueue_scripts.
add_action( 'wp_enqueue_scripts', 'torque_enqueue_stylesheets' );
Once again, take note that the hook name stays the same. Only modify the secondary parameter to match your custom function name.
Conclusion
WordPress comes packed with a huge number of developer-friendly features. However, if you don’t learn how to use them effectively, you will wind up with an unwieldy and unreliable WordPress project.
In this article, you’ve learned about how WordPress templates work together and load in scripts from themes and plugins. Because of this ecosystem, it is super important that your scripts and styles are enqueued properly. This can be done using:
- wp_enqueue_script: For loading in any JavaScript file necessary for your plugin or theme.
- wp_enqueue_style: For registering any CSS files necessary to the front-end design.
What questions do you have about enqueueing files in WordPress? Let us know in the comments section below!
Image Credit: LinkedIn Sales Navigator.
The post The Beginner WordPress Developer’s Guide to wp_enqueue appeared first on Torque.