Skip to content

Instantly share code, notes, and snippets.

@dexit
Forked from igorbenic/shortcode.php
Created April 11, 2024 09:11
Show Gist options
  • Save dexit/32d630dd58a8fe0c5f4e0c293256f528 to your computer and use it in GitHub Desktop.
Save dexit/32d630dd58a8fe0c5f4e0c293256f528 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