I want to check if a post has one of the following shortcodes, wpdocs-shortcode-1, wpdocs-shortcode-2, wpdocs-shortcode-3. If it found any of those shortcodes, then do enqueue scripts and styles.
Basically this code works.
function wpdocs_shortcode_scripts() {
global $post;
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'wpdocs-shortcode') ) {
wp_enqueue_script( 'wpdocs-script');
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts');
What I’d like to achieve is check for more than one shortcodes. I tried the following code by passing an array but it did not work.
function wpdocs_shortcode_scripts() {
global $post;
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, array('wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3') ) {
wp_enqueue_script( 'wpdocs-script');
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts');
Any help would be greatly appreciated.
Thank you so much!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
So yes, as you say you can’t pass an array to has_shortcode, which is confirmed in the docs, so you need to do the ‘OR’ operation manually, which would look something like this:
$shortCodesToTest = [ 'wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3'];
$anyShortCode = false;
foreach ($shortCodesToTest as $sc) {
if (has_shortcode( $post->post_content, $sc) ) {
$anyShortCode = true;
}
}
Now use the $anyShortCode variable as you like – it will be True if any of the shortcodes were found. For example:
if ( is_a( $post, 'WP_Post' ) && $anyShortCode ) {
wp_enqueue_script( 'wpdocs-script');
}
Method 2
You can loop through the shortcuts and then put something into an array when you get a hit.
If the array is not empty at the end, your script can be loaded.
<?php
function wpdocs_shortcode_scripts() {
global $post;
$shortcodes = [ 'wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3' ];
$found = [];
foreach ( $shortcodes as $shortcode ) :
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, $shortcode ) ) {
$found[] = $shortcode;
}
endforeach;
if ( ! empty( $found ) ) {
wp_enqueue_script( 'wpdocs-script' );
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts' );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0