has_shortcode( string $content, string $tag )

Whether the passed content contains the specified shortcode


Description Description


Parameters Parameters

$content

(string) (Required) Content to search for shortcodes.

$tag

(string) (Required) Shortcode tag to check.


Top ↑

Return Return

(bool) Whether the passed content contains the given shortcode.


Top ↑

Source Source

File: wp-includes/shortcodes.php

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

Top ↑

Changelog Changelog

Changelog
Version Description
3.6.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note content
    Contributed by Codex

    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');
    

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