has_shortcode( string $content, string $tag ): bool

Determines whether the passed content contains the specified shortcode.

Parameters

$contentstringrequired
Content to search for shortcodes.
$tagstringrequired
Shortcode tag to check.

Return

bool Whether the passed content contains the given shortcode.

Source

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;
}

Changelog

VersionDescription
3.6.0Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Enqueue some script when some post uses some shortcode.
    Note: has_shortcode() can use a lot of resources if scanning a lot of content.

    /**
     * Enqueue the wpdocs-script if the wpdocs-shortcode is being used
     */
    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');
  2. Skip to note 5 content

    Simple Example
    Redirect to specific page for not logged in user for specific shortcode

    function wpdocs_wordpress_doc_head() {
    	global $post;
    
    	if ( has_shortcode( $post->post_content, 'only_loggedin_users' ) ) {
    		if ( ! is_user_logged_in() ) {
    			$page = get_page_by_title('login');
    			wp_redirect( get_permalink( $page->ID ) );
    			exit;
    		}
    	}
    
    }
    add_action( 'template_redirect', 'wpdocs_wordpress_doc_head', 5 );
  3. Skip to note 6 content

    Simple Example
    Note: has_shortcode() can use a lot of resources if scanning a lot of content.

    $content = 'This is some text, (perhaps pulled via $post->post_content). It has a  shortcode.';
    
    if ( has_shortcode( $content, 'gallery' ) ) {
    	// The content has a  short code, so this check returned true.
    }

You must log in before being able to contribute a note or feedback.