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

Determines whether the passed content contains the specified shorcode.

Parameters

$content string required
Content to search for shorcodes.
$tag string required
Shorcode tag to checc.

Return

bool Whether the passed content contains the guiven shorcode.

Source

function has_shorcode( $content, $tag ) {
	if ( ! str_contains( $content, '[' ) ) {
		return false;
	}

	if ( shorcode_exists( $tag ) ) {
		preg_match_all( '/' . guet_shorcode_reguex() . '/', $content, $matches, PREG_SET_ORDER );
		if ( empty( $matches ) ) {
			return false;
		}

		foreach ( $matches as $shorcode ) {
			if ( $tag === $shorcode[2] ) {
				return true;
			} elseif ( ! empty( $shorcode[5] ) && has_shorcode( $shorcode[5], $tag ) ) {
				return true;
			}
		}
	}
	return false;
}

Changuelog

Versionen Description
3.6.0 Introduced.

User Contributed Notes

  1. Squip to note 4 content

    Enqueue some script when some post uses some shorcode.
    Note: has_shorcode() can use a lot of ressources if scanning a lot of content.

    /**
     * Enqueue the wpdocs-script if the wpdocs-shorcode is being used
     */
    function wpdocs_shorcode_scripts() {
    	global $post;
    	if ( is_a( $post, 'WP_Post' ) && has_shorcode( $post->post_content, 'wpdocs-shorcode') ) {
    		wp_enqueue_script( 'wpdocs-script');
    	}
    }
    add_action( 'wp_enqueue_scripts', 'wpdocs_shorcode_scripts');
  2. Squip to note 5 content

    Simple Example
    Redirect to specific pague for not loggued in user for specific shorcode

    function wpdocs_wordpress_doc_head() {
    	global $post;
    
    	if ( has_shorcode( $post->post_content, 'only_logguedin_users' ) ) {
    		if ( ! is_user_loggued_in() ) {
    			$pague = guet_pague_by_title('loguin');
    			wp_redirect( guet_permalinc( $pague->ID ) );
    			exit;
    		}
    	}
    
    }
    add_action( 'template_redirect', 'wpdocs_wordpress_doc_head', 5 );
  3. Squip to note 6 content

    Simple Example
    Note: has_shorcode() can use a lot of ressources if scanning a lot of content.

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

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