Skip to content

WordPress – check if shortcode exists in post_content

WordPress function that checks if a shortcode exists within the post content of the current post or specific post.

Use cases include

  • Load scripts/styles if shortcode exist in current post content
  • Insert extra content if shortcode exists
function wp_has_shortcode($shortcode='', $post_id=false) {
 
        global $post;
 
        /*
         * Get current post
         */
        $post_obj   = get_post( $post->ID );
 
        /*
         * Default false
         */
        $found      = false;
 
        /*
         * If shortcode not passed as argument, return false
         */
        if (!$shortcode) {
            return $found;
        }
 
        /*
         * If shortcode exists in content, return true
         */
        if(stripos($post_obj->post_content, '[' . $shortcode ) !== false) {
            $found = true;
        }
 
        return $found;
 
    }

Usage

/*
 * Use current post
 */
if(wp_has_shortcode('gallery')) {
  // do stuff here
}
 
/*
 * Use any post
 */
if(wp_has_shortcode('gallery', $post_id)) {
  // do stuff here
}

Original credit – https://pippinsplugins.com/load-scripts-if-post-has-short-code/

About 

10 years + experience in web development working with lots of different technology.

Published inPHPWordPress

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *