There’s already a function for checking if a post has a shortcode: has_shortcode()
:
function enqueue_script_if_shortcode_is_detected() {
global $post;
wp_register_script( 'leweb-widgets', get_stylesheet_directory_uri() . '/includes/leweb-widgets.php', '1.0', true );
if ( has_shortcode( $post->post_content, 'leweb_suggested_events' ) ) {
wp_enqueue_script('leweb-widgets');
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_script_if_shortcode_is_detected' );
Just keep in mind that checking the post this way:
- Will not know if the shortcode is used in a widget or custom field.
- Will not work properly on archive pages.
- Is using the global
$post
variable, which should be avoided where possible. Especially outside the loop.
I’d advise checking is_singular()
and using get_queried_object()
to get the current post.
function enqueue_script_if_shortcode_is_detected() {
wp_register_script( 'leweb-widgets', get_stylesheet_directory_uri() . '/includes/leweb-widgets.php', '1.0', true );
if ( is_singular() ) {
$post = get_queried_object();
if ( has_shortcode( $post->post_content, 'leweb_suggested_events' ) ) {
wp_enqueue_script('leweb-widgets');
}
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_script_if_shortcode_is_detected' );
But if your script is loaded in the footer, which yours is, you’ll get more reliable results if you add wp_enqueue_script('leweb-widgets');
to the shortcode callback. This way you can be sure the script will be loaded whenever the shortcode is used, no matter where it’s used.