Selectively Enqueue Styles and Scripts in WordPress
Enqueue styles and scripts based on whether a shortcode is being used
Only loading the styles and scripts that the shortcode depends on when the shortcode is in use will keep the scripts from being loaded for every other post, keeping the page weight down.
Use has_shortcode()
to determine if the shortcode is being used before calling wp_enqueue_script()
.
Add to a theme's functions.php
file, where my-shortcode
is the name of the shortcode and my_script.js
, referenced as my_script
, is the script to enqueue from the js
directory of the theme.
function enqueue_my_shortcode_scripts() {
global $post;
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'my-shortcode') ) {
wp_enqueue_script( 'my_script', get_template_directory_uri() . '/js/my_script.js', [], '1.0', false );
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_shortcode_scripts');
Enqueue styles and scripts based on whether a taxonomy is being viewed
Use is_tax()
to determine if the taxonomy is being viewed before calling wp_enqueue_script()
.
Add to a theme's functions.php
file, where my-taxonomy-name
is the name of the custom taxonomy and my-taxonomy-name.js
, referenced as my_taxonomy_script
, is the script to enqueue from the js
directory of the theme.
function enqueue_my_taxonomy_scripts() {
if ( is_tax( 'my-taxonomy-name' ) ) {
wp_enqueue_script( 'my_taxonomy_script', get_stylesheet_directory_uri() . '/js/my-taxonomy-name.js', [], '1.0', false );
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_taxonomy_scripts', 99 );
Feedback?
Email us at enquiries@kinsa.cc.