Dorokhov.codes
11. Loading styles and scripts
What hooks should I use?
Hook | Description |
---|---|
wp_enqueue_scripts |
Use this hook to enqueue scripts and styles on the front-end of your site. |
admin_enqueue_scripts |
This hook is used to enqueue scripts and styles in the WordPress admin area. |
login_enqueue_scripts |
Use this hook to enqueue scripts and styles on the WordPress login page. |
Loading scripts and styles
function my_theme_enqueue_scripts() {
// Load a script:
wp_enqueue_script(
'my-script',
get_template_directory_uri() . '/js/my-script.js',
array( 'jquery' )
);
// Load styles:
wp_enqueue_style(
'schedule-settings-page',
get_template_directory_uri() . '/css/styles.css'
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
Paths:
// Inside a theme:
get_template_directory_uri() . '/js/my-script.js';
// Inside a plugin:
plugin_dir_url( __DIR__ ) . 'admin/js/settings-page.js'
Default scripts and libraries
Default Scripts and JS Libraries Included and Registered by WordPress.
Common used:
jquery
.
JavaScript
When you enqueue script that is dependent on
jQuery
, note that thejQuery
in WordPress runs innoConflict
mode, which means you cannot use the common$
alias. You must use the fulljQuery
instead. Alternately, place your code using the$
shortcut inside a noConflict wrapper.
jQuery( document ).ready( function( $ ) {
// $() will work as an alias for jQuery() inside this function
} );
Two ways of passing variables to JS
First way
wp_localize_script( string $handle, string $object_name, array $l10n )
Example:
wp_localize_script('hitpay-settings-page', 'app', [
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'author' => 'Andrew Dorokhov',
]);
jQuery(document).ready(function($) {
console.log(app.ajaxUrl);
console.log(app.author);
});
Second way
wp_add_inline_script( string $handle, string $data, string $position = 'after' )
Example:
$js = 'const app = ' . json_encode( [
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'author' => 'Andrew Dorokhov',
] );
wp_add_inline_script( 'hitpay-settings-page', $js, 'before' );
Conditions
Check if the current admin page belongs to our plugin:
function enqueue_scripts( $hook_suffix ) {
if ( 'toplevel_page_schedule' != $hook_suffix ) {
return;
}
wp_enqueue_script( /* ... */ );
}
add_action( 'admin_enqueue_scripts', 'enqueue_scripts' );
Load scrips only for some shortcode:
function add_address_processing() {
global $post;
if ( ! has_shortcode( $post->post_content, 'mepr-membership-registration-form' ) ) {
return;
}
wp_enqueue_script( /* ... */ );
}
add_action( 'wp_enqueue_scripts', 'add_address_processing' );