wordpresstemplatesplugins

Using Wordpress has_shortcode to detect do_shortcode


I have a template file where I am using do_shortcode() to execute a short code.

In the template file I have:

<html>
...
<?php do_shortcode( '[my_shortcode]' ); ?>
...
</html>

I have used the following code in my functions:

function my_function() {
 if ( has_shortcode( $post->post_content, 'my_shortcode' ) ) {
    //do stuff here (i.e. load stylesheet for shortcode content)
 }
}

If I am not mistaken, $post->post_content (or the get_the_content() function) return only the post/page content, not the template. How do I get the entire content into has_shortcode?


Solution

  • Thanks to comments from @mmm, I figured out (or found) the answer to my question.

    https://wordpress.org/support/topic/enqueue-scripts-and-styles-via-shortcode/

    Basically, you can call wp_enqueue_style or wp_enqueue_script within the callback for the shortcode itself.

    <?php
    
    add_shortcode( 'shortcode' , 'shortcode_callback' );
    
    function shortcode_callback() {
    
         wp_enqueue_style( 'style-slug' , 'path-to-stylesheet.css' );
    
         $output = ...html here...
    
         return $output;
    
    }
    

    So whether your shortcode is called within a post/page or by using do_shortcode() in a template file, any stylesheet or script file your shortcode needs will be enqueued, but only if the shortcode is used.