WordPress Enqueue Scripts and Styles
Never write <link> or <script> tags by hand in header.php. WordPress has a proper system to load CSS and JavaScript files, called enqueue. It stops the same file from loading two times, loads files in the right order and lets plugins change them.
Enqueue a stylesheet and a script
Use the hook wp_enqueue_scripts in functions.php:
<?php
function tc_enqueue_assets() {
// main style.css of the theme
wp_enqueue_style( 'tc-style', get_stylesheet_uri(), array(), '1.0' );
// our own script, loaded in the footer, needs jQuery
wp_enqueue_script(
'tc-main',
get_template_directory_uri() . '/js/main.js',
array( 'jquery' ),
'1.0',
true
);
}
add_action( 'wp_enqueue_scripts', 'tc_enqueue_assets' );
$ curl -s http://example.com/ | grep -E "tc-style|tc-main|jquery" | sed 's/^[ \t]*//'
<link rel='stylesheet' id='tc-style-css' href='http://example.com/wp-content/themes/tc-theme/style.css?ver=1.0' media='all' />
<script id="jquery-core-js" src="http://example.com/wp-includes/js/jquery/jquery.min.js?ver=3.7.1"></script>
<script id="jquery-migrate-js" src="http://example.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=3.4.1"></script>
<script id="tc-main-js" src="http://example.com/wp-content/themes/tc-theme/js/main.js?ver=1.0"></script>
WordPress printed the tags for us. The word after ver= is the version we gave. When you change the file, change the version too, so the browser takes the new file and not the old cached one.
The function parameters
| Parameter | Meaning |
|---|---|
| $handle | A unique name for the file, like tc-main |
| $src | The full URL of the file |
| $deps | An array of handles which must load before it, like array( 'jquery' ) |
| $ver | Version, used for cache busting. False uses the WordPress version, null adds nothing |
| $in_footer (script) | true loads the script before the closing body tag |
| $media (style) | Media type, like all or print |
Pass data from PHP to JavaScript
Use wp_add_inline_script() (or wp_localize_script() for older code) to send values like the AJAX address to your script:
wp_add_inline_script(
'tc-main',
'const tcData = ' . wp_json_encode( array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ) ) ) . ';',
'before'
);
Load only where needed
Do not load a big script on all pages when you need it on one page. Use conditional tags inside the function:
if ( is_page( 'contact' ) ) {
wp_enqueue_script( 'tc-contact', get_template_directory_uri() . '/js/contact.js', array(), '1.0', true );
}
Admin side
The dashboard has its own hook: admin_enqueue_scripts. For the login page use login_enqueue_scripts. For the block editor, use enqueue_block_editor_assets.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |