3

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;
    }
}
2
3

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.

1

You can pre-check for the presence of the shortcode in the post content and enqueue the script in the header if it is found.

However, you must also fallback to adding it in the footer because the shortcode may be run from elsewhere (eg. in a widget, a template or programmatically.)

public function __construct() {
    add_shortcode('cbwsppb', array($this => 'shortcode_func'));
    add_action('wp', array($this => 'shortcode_check'));
}

public function shortcode_check() {
    if (is_single() && (is_product()) {
        global $post; $content = $post->post_content;

        // global $wpdb;
        // $query = "SELECT 'post_content' FROM "'.$wpdb->prefix.'"posts WHERE ID = '".$post->ID."'";
        // $content = $wpdb->get_var($query);

        // quick and dirty check for shortcode in post content
        if ( (stristr($content,'[cbwsppb')) 
          && (stristr($content,'display_style')) 
          && (stristr($content,'carousel')) ) {
            add_action('wp_enqueue_scripts', array($this,'enqueue_styles'));
        }
    }
}

public function enqueue_styles() {
    wp_enqueue_style('flexslider-style');
}

public function shortcode_func($atts, $content = null) {

   // ... $atts = shortcode_atts etc ...

   // change this to:
   if ( ($atts['display_style'] === 'carousel')
      && (!wp_style_is('flexslider-style','enqueued')) ) {
       wp_enqueue_style('flexslider-style');
   }

   // ... the rest of the shortcode function ...
}
2
  • I like how you've added instructions for loading conditionally, but is going through the database directly really the best idea? Can't you just use $post->post_content or something similar? – shea Feb 26 '17 at 5:30
  • @shea good pickup, yeah it's an unnecessary extra query, I've edited it out. – majick Feb 26 '17 at 9:14
0

You should try this :

function prefix_add_styles() {
    wp_enqueue_style( 'your-style-id', get_template_directory_uri() . '/stylesheets/somestyle.css' );
};
add_action( 'get_header', 'prefix_add_styles' );
1
  • 1
    Please edit your answer, and add an explanation: why could that solve the problem? – fuxia Feb 17 '17 at 14:14
0

Try below code. Refer from wp_enqueue_style.

   function my_shortcode_style(){
      wp_enqueue_style( 'my_css', plugin_dir_url( __FILE__ ).'style.css', array( '' ), false, 'all' );
   }
   add_action('wp_enqueue_scripts', 'my_shortcode_style');

Note: For your plugin directory path use plugin_dir_url() and for current theme path use get_template_directory_uri()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.