Best Practice for Enqueuing Scripts and Styles
Custom Code Solution
The proper way to add custom CSS and JavaScript files is using WordPress's wp_enqueue_scripts
hook with the wp_enqueue_style()
and wp_enqueue_script()
functions.
Place this code in your theme's functions.php
file or in your plugin's main PHP file:
Basic enqueue setup for both CSS and JavaScript files:
function theme_custom_enqueue() {
// Enqueue CSS
wp_enqueue_style(
'custom-style',
get_template_directory_uri() . '/assets/css/custom.css',
array(),
'1.0.0'
);
// Enqueue JavaScript
wp_enqueue_script(
'custom-script',
get_template_directory_uri() . '/assets/js/custom.js',
array('jquery'),
'1.0.0',
true
);
}
add_action('wp_enqueue_scripts', 'theme_custom_enqueue');
Enqueue script with localized data (passing PHP variables to JavaScript):
function theme_script_with_data() {
wp_enqueue_script(
'custom-script',
get_template_directory_uri() . '/assets/js/custom.js',
array('jquery'),
'1.0.0',
true
);
$script_data = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'security' => wp_create_nonce('custom-security-nonce')
);
wp_localize_script('custom-script', 'customData', $script_data);
}
add_action('wp_enqueue_scripts', 'theme_script_with_data');
Conditional enqueuing (load scripts only on specific pages):
function theme_conditional_enqueue() {
// Load only on single posts
if (is_single()) {
wp_enqueue_style(
'single-post-style',
get_template_directory_uri() . '/assets/css/single-post.css',
array(),
'1.0.0'
);
}
// Load only on contact page
if (is_page('contact')) {
wp_enqueue_script(
'contact-form-script',
get_template_directory_uri() . '/assets/js/contact-form.js',
array('jquery'),
'1.0.0',
true
);
}
}
add_action('wp_enqueue_scripts', 'theme_conditional_enqueue');
Important Notes:
- File paths should be relative to your theme or plugin directory
- Version numbers help with cache busting
- The
true
parameter in wp_enqueue_script()
loads the script in the footer
- Always use dependencies array if your script relies on other scripts
- Use conditional loading to optimize page load speed
Plugin Solutions
If you prefer a plugin solution, these options are reliable:
-
Assets Manager - Manage all your scripts and styles through the admin panel
-
Scripts-To-Footer - Moves all scripts to footer for better performance
-
Plugin Organizer - Selectively load scripts and styles on specific pages
Best Practices:
- Always use WordPress enqueue functions instead of directly adding
<script>
or <link>
tags
- Properly declare dependencies to prevent conflicts
- Use conditional loading when possible
- Include version numbers for cache control
- Place scripts in footer when possible for better page load performance