📦 Enqueuing Styles & Scripts
The WordPress way to add CSS and JavaScript
Master proper asset management in WordPress themes
Learning Objectives
- Understand why enqueuing is important
- Master wp_enqueue_style() and wp_enqueue_script()
- Manage script and style dependencies
- Learn proper versioning and caching strategies
- Implement conditional loading
- Work with external CDN resources
- Localize scripts for AJAX
- Dequeue and deregister assets
- Optimize loading performance
Why Enqueue?
WordPress uses an enqueuing system to manage CSS and JavaScript files. This prevents conflicts, manages dependencies, and ensures scripts load in the correct order.
Key Concept
The Enqueue Process
1. Register
→
Define the asset
2. Enqueue
→
Add to queue
3. Dependencies
→
Check requirements
4. Output
Print in HTML
Basic Enqueuing
Enqueuing Styles
Basic Style Enqueue
<?php
function mytheme_enqueue_styles() {
// Main theme stylesheet (style.css)
wp_enqueue_style(
'mytheme-style', // Handle
get_stylesheet_uri(), // Source
array(), // Dependencies
'1.0.0', // Version
'all' // Media
);
// Additional stylesheet
wp_enqueue_style(
'mytheme-custom',
get_template_directory_uri() . '/assets/css/custom.css',
array('mytheme-style'), // Depends on main style
filemtime(get_template_directory() . '/assets/css/custom.css'), // Auto version
'all'
);
// Conditional stylesheet for print
wp_enqueue_style(
'mytheme-print',
get_template_directory_uri() . '/assets/css/print.css',
array(),
'1.0.0',
'print' // Only for print media
);
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_styles' );
Enqueuing Scripts
Basic Script Enqueue
<?php
function mytheme_enqueue_scripts() {
// Deregister WordPress jQuery and use custom version (not recommended)
// wp_deregister_script( 'jquery' );
// Main theme script
wp_enqueue_script(
'mytheme-main', // Handle
get_template_directory_uri() . '/assets/js/main.js', // Source
array('jquery'), // Dependencies
'1.0.0', // Version
true // In footer
);
// Vendor script
wp_enqueue_script(
'mytheme-vendor',
get_template_directory_uri() . '/assets/js/vendor.min.js',
array(), // No dependencies
'1.0.0',
true
);
// Custom script with multiple dependencies
wp_enqueue_script(
'mytheme-custom',
get_template_directory_uri() . '/assets/js/custom.js',
array('jquery', 'mytheme-vendor', 'mytheme-main'),
filemtime(get_template_directory() . '/assets/js/custom.js'),
true
);
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_scripts' );
Function Parameters
wp_enqueue_style() Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
$handle |
string | Yes | Unique name for the stylesheet |
$src |
string | No | Full URL or path to stylesheet |
$deps |
array | No | Array of handles this stylesheet depends on |
$ver |
string|bool | No | Version number (false for no version) |
$media |
string | No | Media type ('all', 'screen', 'print', etc.) |
wp_enqueue_script() Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
$handle |
string | Yes | Unique name for the script |
$src |
string | No | Full URL or path to script |
$deps |
array | No | Array of handles this script depends on |
$ver |
string|bool | No | Version number (false for no version) |
$in_footer |
bool | No | Load in footer (true) or header (false) |
Managing Dependencies
Dependency Chain Example
jQuery (Core)
↓
Bootstrap JS
(depends on jQuery)
↓
Theme Main JS
(depends on Bootstrap)
↓
Custom JS
(depends on Main JS)
Complex Dependencies Example
<?php
function mytheme_scripts_with_deps() {
// Register scripts first (optional but recommended for complex deps)
wp_register_script(
'bootstrap-js',
get_template_directory_uri() . '/assets/js/bootstrap.min.js',
array('jquery'),
'5.0.0',
true
);
wp_register_script(
'slick-slider',
get_template_directory_uri() . '/assets/js/slick.min.js',
array('jquery'),
'1.8.1',
true
);
wp_register_script(
'lightbox',
get_template_directory_uri() . '/assets/js/lightbox.min.js',
array('jquery'),
'2.11.3',
true
);
// Main script depends on all libraries
wp_enqueue_script(
'mytheme-main',
get_template_directory_uri() . '/assets/js/main.js',
array('jquery', 'bootstrap-js', 'slick-slider', 'lightbox'),
'1.0.0',
true
);
// Styles with dependencies
wp_enqueue_style(
'bootstrap-css',
get_template_directory_uri() . '/assets/css/bootstrap.min.css',
array(),
'5.0.0'
);
wp_enqueue_style(
'mytheme-style',
get_stylesheet_uri(),
array('bootstrap-css'), // Depends on Bootstrap CSS
'1.0.0'
);
}
add_action( 'wp_enqueue_scripts', 'mytheme_scripts_with_deps' );
Conditional Asset Loading
Load assets only where needed to improve performance.
Conditional Enqueuing Examples
<?php
function mytheme_conditional_scripts() {
// Load only on front page
if ( is_front_page() ) {
wp_enqueue_script(
'mytheme-hero-slider',
get_template_directory_uri() . '/assets/js/hero-slider.js',
array('jquery'),
'1.0.0',
true
);
}
// Load only on single posts
if ( is_single() ) {
wp_enqueue_script(
'mytheme-comments',
get_template_directory_uri() . '/assets/js/comments.js',
array('jquery'),
'1.0.0',
true
);
}
// Load only on pages with specific template
if ( is_page_template('template-contact.php') ) {
wp_enqueue_script(
'google-maps',
'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY',
array(),
null,
true
);
wp_enqueue_script(
'mytheme-contact',
get_template_directory_uri() . '/assets/js/contact.js',
array('jquery', 'google-maps'),
'1.0.0',
true
);
}
// Load only if WooCommerce is active and on shop pages
if ( class_exists('WooCommerce') && is_shop() ) {
wp_enqueue_script(
'mytheme-shop',
get_template_directory_uri() . '/assets/js/shop.js',
array('jquery'),
'1.0.0',
true
);
}
// Load only for logged-in users
if ( is_user_logged_in() ) {
wp_enqueue_script(
'mytheme-user-dashboard',
get_template_directory_uri() . '/assets/js/dashboard.js',
array('jquery'),
'1.0.0',
true
);
}
// Load different styles for different post types
if ( is_singular('portfolio') ) {
wp_enqueue_style(
'mytheme-portfolio',
get_template_directory_uri() . '/assets/css/portfolio.css',
array(),
'1.0.0'
);
}
}
add_action( 'wp_enqueue_scripts', 'mytheme_conditional_scripts' );
Script Localization (AJAX)
Pass PHP data to JavaScript using wp_localize_script().
Localizing Scripts for AJAX
<?php
function mytheme_enqueue_ajax_script() {
// Enqueue the script
wp_enqueue_script(
'mytheme-ajax',
get_template_directory_uri() . '/assets/js/ajax.js',
array('jquery'),
'1.0.0',
true
);
// Localize the script with data
wp_localize_script(
'mytheme-ajax', // Script handle
'mytheme_ajax_object', // Object name in JS
array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('mytheme_ajax_nonce'),
'site_url' => home_url(),
'theme_url' => get_template_directory_uri(),
'is_mobile' => wp_is_mobile(),
'is_logged_in' => is_user_logged_in(),
'current_user_id' => get_current_user_id(),
'strings' => array(
'loading' => __('Loading...', 'mytheme'),
'error' => __('An error occurred', 'mytheme'),
'success' => __('Success!', 'mytheme'),
'confirm' => __('Are you sure?', 'mytheme'),
),
'settings' => array(
'animation_speed' => 300,
'posts_per_page' => get_option('posts_per_page'),
'date_format' => get_option('date_format'),
)
)
);
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_ajax_script' );
// JavaScript usage:
// console.log(mytheme_ajax_object.ajax_url);
// console.log(mytheme_ajax_object.strings.loading);
JavaScript AJAX Implementation
// ajax.js
jQuery(document).ready(function($) {
$('#load-more-btn').on('click', function() {
var button = $(this);
$.ajax({
url: mytheme_ajax_object.ajax_url,
type: 'POST',
data: {
action: 'load_more_posts',
nonce: mytheme_ajax_object.nonce,
page: button.data('page')
},
beforeSend: function() {
button.text(mytheme_ajax_object.strings.loading);
},
success: function(response) {
if (response.success) {
$('#posts-container').append(response.data.html);
button.data('page', response.data.next_page);
} else {
alert(mytheme_ajax_object.strings.error);
}
},
error: function() {
alert(mytheme_ajax_object.strings.error);
},
complete: function() {
button.text('Load More');
}
});
});
});
Working with CDN Resources
How to properly enqueue external libraries from CDNs.
CDN Enqueuing with Fallback
<?php
function mytheme_enqueue_cdn_scripts() {
// Google Fonts
wp_enqueue_style(
'google-fonts',
'https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&display=swap',
array(),
null
);
// Font Awesome from CDN
wp_enqueue_style(
'font-awesome',
'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css',
array(),
'6.0.0'
);
// jQuery from CDN with local fallback
wp_deregister_script('jquery');
wp_register_script(
'jquery',
'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js',
array(),
'3.6.0',
true
);
wp_enqueue_script('jquery');
// Add fallback for jQuery
wp_add_inline_script(
'jquery',
'window.jQuery || document.write(\'