Using WordPress ‘has_shortcode()’ PHP function

The has_shortcode() WordPress PHP function determines whether the passed content contains the specified shortcode.

Usage

has_shortcode( $content, $tag )

Example:

Input: has_shortcode( 'This is a sample text with [my_shortcode].', 'my_shortcode' )

Output: true

Parameters

  • $content (string) – Required. Content to search for shortcodes.
  • $tag (string) – Required. Shortcode tag to check.

More information

See WordPress Developer Resources: has_shortcode()

Examples

Enqueue a script if the shortcode is being used

This code enqueues the ‘wpdocs-script’ if the ‘wpdocs-shortcode’ is present in the post content.

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

Redirect to a specific page for non-logged-in users for a specific shortcode

This code redirects non-logged-in users to a login page when the ‘only_loggedin_users’ shortcode is present in the post content.

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

Check if the content has a specific shortcode

This code checks if the content has a ‘gallery’ shortcode.

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

Check for multiple shortcodes in a content

This code checks if the content has either ‘shortcode1’ or ‘shortcode2’ and performs some action accordingly.

$content = 'This is some text with [shortcode1] and [shortcode2].';

if ( has_shortcode( $content, 'shortcode1' ) ) {
  // The content has a [shortcode1], so do something.
}

if ( has_shortcode( $content, 'shortcode2' ) ) {
  // The content has a [shortcode2], so do something else.
}

Display a message if a shortcode is present

This code displays a message if the ‘my_shortcode’ is present in the content.

$content = 'This is some text with [my_shortcode].';

if ( has_shortcode( $content, 'my_shortcode' ) ) {
  echo "The content has a [my_shortcode].";
}