has_shortcode()WP 3.6.0

Whether the passed content contains the specified shortcode

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.

Return

true|false. Whether the passed content contains the given shortcode.

Usage

has_shortcode( $content, $tag );
$content(string) (required)
Content to search for shortcodes.
$tag(string) (required)
Shortcode tag to check.

Examples

0

#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.
}
0

#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');
	}
}
0

#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.

Code of has_shortcode() WP 5.9.3

function has_shortcode( $content, $tag ) {
	if ( false === strpos( $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;
}