has_shortcode( string $content, string $tag ): bool
Determines whether the passed content contains the specified shortcode.
Parameters
-
$content
string Required -
Content to search for shortcodes.
-
$tag
string Required -
Shortcode tag to check.
Return
bool Whether the passed content contains the given shortcode.
Source
File: wp-includes/shortcodes.php
.
View all references
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
Version | Description |
---|---|
3.6.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
Enqueue some script when some post uses some shortcode.
Note:
has_shortcode()
can use a lot of resources if scanning a lot of content.Top ↑
Feedback
Instead of the `global $post` which requires the `is_a($post, ‘WP_Post’)` check, simply using `get_the_content()` works fine too. — By Alec —
Simple Example
Redirect to specific page for not logged in user for specific shortcode
Simple Example
Note:
has_shortcode()
can use a lot of resources if scanning a lot of content.