Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Created November 11, 2020 11:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save igorbenic/3d82a5b09300f43a6a2937dec5a28afa to your computer and use it in GitHub Desktop.
Save igorbenic/3d82a5b09300f43a6a2937dec5a28afa to your computer and use it in GitHub Desktop.
Conditional Enqueueing of scripts in WordPress
<?php
add_action('wp_enqueue_scripts', 'enqueue_if_shortcode');
function enqueue_if_shortcode(){
global $post;
if ( $post && has_shortcode( $post->post_content, 'your_shortcode_tag' ) {
// Enqueue
}
}
<?php
add_action('wp_enqueue_scripts', 'enqueue_if_widget');
function enqueue_if_widget(){
// widget base id in https://codex.wordpress.org/Widgets_API#Default_Usage is 'my_widget'
// check https://developer.wordpress.org/reference/functions/is_active_widget/ for more info
if ( is_active_widget(false, false, 'your_widget_base_id', true) ) {
// enqueue your scripts;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment