Enqueue style inside shortcode but its loaded at the bottom of page (before footer scripts)

I added/enqueue a style inside shortcode, it works fine but loaded in footer (before starting the .js files) rather than header. I did the same way like this solution:

Enqueue Scripts / Styles when shortcode is present

Is it normal in WP or how can I load style in header ?

Sample Code Here:

class Cbwsppb_Related {

    public function __construct() 
    {
        add_shortcode('cbwsppb_related', array($this, 'shortcode_func'));
    }

    public function shortcode_func($atts, $content = null) 
    {
        $atts = shortcode_atts( array(
          'style'    => '',
          'display_style'    => '',
          'show'    => '',
          'orderby' => ''
        ), $atts );

        if ($atts['display_style'] === 'carousel') {
            wp_enqueue_style('flexslider-style');
        }

        $show = (!empty($atts['show'])) ? $atts['show'] : 2;
        $orderby = (!empty($atts['orderby'])) ? $atts['orderby'] : 'rand';

        $output="";
        ob_start();

            if ($atts['style'] === 'custom') {
                $output .= woocommerce_get_template( 'single-product/related.php', array(
                        'posts_per_page' => $show,
                        'orderby' => $orderby,
                    ) 
                );                 
            } else {
                $output .= woocommerce_get_template( 'single-product/related.php');                
            }

            $output .= ob_get_clean();
        return $output;
    }
}

4 Answers
4

Why it is added in the footer:

This is the expected behaviour.

Since you have enqueued the style within your Shortcode hook function, by the time it executes, WordPress is already done generating the <head> section of your page, since WordPress will only execute your shortcode function once it has found the shortcode in your content.

So it has no other way than to place your style in the footer section if you enqueue style within the shortcode hook function.

How to add it in the header:

If you want to output it in <head> section, you must enqueue it using:

function enqueue_your_styles() {
    // the following line is just a sample, use the wp_enqueue_style line you've been using in the shortcode function 
    wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/css/your-style.css' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_your_styles' );

Note: this will add the style even if you don’t have the shortcode in the page.

Note-2: One of the answers in the question you’ve mentioned already have a detailed explanation on alternatives and pros & cons.

Leave a Comment