has_shortcode()
Checks if the specified shortcode exists in the given text.
The shortcode must be registered via the function add_shotrcode() for it to be recognized by WordPress.
Used By: get_post_galleries()
1 time — 0.000014 sec (very fast) | 50000 times — 0.03 sec (speed of light) | PHP 7.0.8, WP 4.6.1
No Hooks.
Returns
true|false. Whether the shortcode was found in the text or not.
Usage
if ( has_shortcode( $content, $tag ) ) {
}
- $content(string) (required)
- The text to check.
- $tag(string) (required)
- The name of the shortcode to find in the text.
Examples
#1 Сheck if there are any gallery in post
$content = 'This is some text, (possibly passed in via $post->post_content).
It contains a shortcode: [gallery].';
if( has_shortcode( $content, 'gallery' ) ) {
// [gallery] is in the passed text.
} #2 Selective script connection, based on the presence of a shortcode in the post content
Connect the javascript (custom-script) only if the gallery shortcode is found in the post content:
add_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts' );
function custom_shortcode_scripts() {
global $post;
$has_gallery = $post && has_shortcode( $post->post_content, 'gallery' );
if( $has_gallery ) {
wp_enqueue_script( 'custom-script');
}
} #3 Redirect to specific page for not logged in user for specific shortcode
Redirect to 'login' page if [only_loggedin_users] short-code presents in post content.
add_action( 'template_redirect', 'wp_kama_wordpress_doc_head', 5 );
function wp_kama_wordpress_doc_head() {
global $post;
if( is_user_logged_in() ){
return;
}
$do_redirect = $post && has_shortcode( $post->post_content, 'only_loggedin_users' );
if ( $do_redirect ) {
$page = get_page_by_title( 'login' );
wp_redirect( get_permalink( $page->ID ) );
exit;
}
}
Notes
- Global. Array. $shortcode_tags
Changelog
| Since 3.6.0 | Introduced. |
has_shortcode() has shortcode code WP 6.8.3
function has_shortcode( $content, $tag ) {
if ( ! str_contains( $content, '[' ) ) {
return false;
}
if ( shortcode_exists( $tag ) ) {
preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER );
if ( empty( $matches ) ) {
return false;
}
foreach ( $matches as $shortcode ) {
if ( $tag === $shortcode[2] ) {
return true;
} elseif ( ! empty( $shortcode[5] ) && has_shortcode( $shortcode[5], $tag ) ) {
return true;
}
}
}
return false;
}