Enqueueing Styles and Scripts
December 14, 2024 · AI Conversations
### Enqueuing Styles
To enqueue a CSS file, use the `wp_enqueue_style()` function:
function my_theme_enqueue_styles() {
wp_enqueue_style(
'my-custom-style', // Unique handle for the stylesheet
get_stylesheet_directory_uri() . '/css/custom-style.css', // Path to the CSS file
array(), // Dependencies (if any)
'1.0', // Version number
'all' // Media type (all, screen, print, etc.)
);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');
### Enqueuing Scripts
To enqueue a JavaScript file, use the `wp_enqueue_script()` function:
function my_theme_enqueue_scripts() {
wp_enqueue_script(
'my-custom-script', // Unique handle for the script
get_template_directory_uri() . '/js/custom-script.js', // Path to the JS file
array('jquery'), // Dependencies (jQuery in this case)
'1.0', // Version number
true // Load in the footer (true) or head (false)
);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');
### Full Example
Here’s how you can combine both style and script enqueues in your `functions.php`:
function my_theme_enqueue_assets() {
// Enqueue CSS
wp_enqueue_style(
'my-custom-style',
get_stylesheet_directory_uri() . '/css/custom-style.css',
array(),
'1.0',
'all'
);
// Enqueue JavaScript
wp_enqueue_script(
'my-custom-script',
get_template_directory_uri() . '/js/custom-script.js',
array('jquery'),
'1.0',
true
);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_assets');
### Notes
– Make sure to replace the paths in `get_stylesheet_directory_uri()` and `get_template_directory_uri()` with the actual paths to your CSS and JS files.
– The third parameter of `wp_enqueue_script()` allows you to specify dependencies. If your script depends on jQuery, you can include it as shown.
– The last parameter of `wp_enqueue_script()` determines whether the script is loaded in the footer (`true`) or the header (`false`).
This should get you started with enqueueing styles and scripts in WordPress! Let me know if you have any questions.