1

I am trying to include bootstrap only when the short-code function executes. It gets included but it affects the other tags of the theme.

The only way I can get around this is including bootstrap globally in the plugin's primary file. It works on the front end, making the short-code execute and display output with bootstrap classes and all of the other page content is not affected by bootstrap.

But this way, these are included everywhere and this affects the back-end styles.

The problem is tied to both front and back ends. If one is fixed, the other gets broken.

2 Answers 2

1

I also find the typical practice of queuing globally or from inside shortcodes problematic.

I had a similar challenge with implementing code highlight on my site — I only wanted scripts and style to load as necessary. I ended up checking content for <pre> tag as condition to output:

{% if '<pre>' in get_the_content() %}
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/solarized_dark.min.css">
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script>
    {% if has_term( 'twig', 'post_tag' ) %}
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/languages/twig.min.js"></script>
    {% endif %}
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            $('pre').each(function (i, e) {
                hljs.highlightBlock(e)
            });
        });
    </script>
{% endif %}

This is in Twig template (and doesn't use WP queue), but you can use same approach in PHP just as well.

0

First outside your shortcode callback function just register the stylsheet and then in shortcode callback function enqueue it. like:-

    function wpsoe_191512_avatar_shortcode_wp_enqueue_scripts() {
  wp_register_style( 'get-avatar-style', plugins_url( '/css/style.css' , __FILE__ ), array(), '1.0.0', all );
  }


  add_action( 'wp_enqueue_scripts', 'brw_avatar_shortcode_wp_enqueue_scripts' );

  if ( function_exists( 'get_avatar' ) ) {

  function wpse_165754_user_avatar_shortcode ( $attributes ) {
            global $current_user;
            get_currentuserinfo();
            extract(shortcode_atts(array(
             "id" => $current_user->ID,
             "size" => 32,
             "default" => 'mystery',
             "alt" => '',
             "class" => '',
      ), 
      $attributes, 'get_avatar' ));
      $get_avatar= get_avatar( $id, $size, $default, $alt );

      wp_enqueue_style( 'get-avatar-style' );

      return '<span class="get_avatar '.$class.'">'.$get_avatar.'</span>';
      }
      add_shortcode ('get_avatar', 'wpse_165754_user_avatar_shortcode');
      }

Above is the example. You can use yours. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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