Recently, I needed to check for the existence of several related shortcodes within WordPress. Rather than writing a large if-or statement I came up with this small function that takes in an array of strings and a boolean to determine whether I needed to check for the existence of all the supplied shortcodes or just any of them.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Loop through an array of shortcodes and check for their existence | |
* @author Gabe Shackle <gabe@hereswhatidid.com> | |
* @param array $shortcodes An array of shortcode strings | |
* @param boolean $match_all Whether to check for the existence of ALL the shortcodes, or just ANY of them | |
* @return mixed The results will either be an array of the found shortcodes or boolean false | |
*/ | |
function shortcodes_exist( $shortcodes = array(), $match_all = false ) { | |
$found_shortcodes = array(); | |
foreach( $shortcodes as $shortcode ) { | |
if ( shortcode_exists( $shortcode ) ) { | |
$found_shortcodes[] = $shortcode; | |
} else { | |
if ( $match_all ) { | |
return false; | |
} | |
} | |
} | |
if ( count( $found_shortcodes ) === 0 ) { | |
return false; | |
} else { | |
return $found_shortcodes; | |
} | |
} | |
$shortcodes_to_find = array( | |
'gallery', | |
'audio', | |
'thiswontwork' | |
); | |
$find_any = shortcodes_exist( $shortcodes_to_find ); | |
// returns array( 'gallery', 'audio' ); | |
$find_all = shortcodes_exist( $shortcodes_to_find, true ); | |
// returns false |