how to include other plugins css files in a shortcode?

I think you could get around this by pre-running the shortcodes on the page by applying the content filters before the header is output. This should allow any internal shortcodes run inside the included post to add any action hooks properly and thus any needed stylesheets/resources.

add_action('wp_loaded','maybe_prerun_shortcodes');
function maybe_prerun_shortcodes() {
    if (is_page()) {
        global $post; 
        if (has_shortcode($post->post_content,'embed_post')) {
            $content = apply_filters('the_content',$post->post_content);
        }
    }
}

EDIT The above will only enqueue stylesheets and resources that are enqueued within any shortcode calls in the embedded post (which, although it is better practice, is actually not done very often.) It should work for those cases because applying the filters to the current page content will run the embed shortcode which then applies filters for the embedded post (in your existing function.)

However, To get the stylesheets for a particular post you would have to fetch that particular post (which is why the iframe method works, well kind of, given the problems already discussed about that.)

My suggested workaround in that case is to store the style resources loaded on a post when the post is loaded…

add_filter('style_loader_tag','custom_store_style_tags',11,2)
function custom_store_style_tags($tag,$handle) {
    global $styletags; $styletags[$handle] = $tag;}
}

add_action('wp_footer','custom_save_style_tags');
function custom_save_style_tags() {
    global $embedstyles;
    if (is_single()) {
        global $styletags, $post; 
        update_post_meta($post->ID,'styletags',$styletags);
    } elseif (is_array($embedstyles)) {
        global $styletags;
        foreach ($embedstyles as $handle => $tag) {
            if (!array_key_exists($handle,$styletags)) {echo $tag;}
        }
    }
}

Then you can use the shortcode to retrieve the style tags to be retrieved and the second part of the above function will output them in the footer:

public static function myshortcode($atts = null, $content = "")
{
  // EXISTING CODE SNIPPED

  global $embedstyles;
  $embedstyle = get_post_meta($post_id,'styletags',true);
  if (is_array($embedstyle)) {
      if (!is_array($embedstyles)) {$embedstyles = array();}
      $embedstyles = array_merge($embedstyle,$embedstyles);
  }

  return $content;
}

And you could do the same for scripts via script_loader_tag filter and simply changing the variables to match…

Of course there is still the possibility some body classes may not be targeted by styles as already mentioned by @cjbj… or some scripts may initialize in the footer even if they are enqueued properly.

…and it does not account for inline styles/scripts printed (not enqueued) on the page yet… but it’s a good start… depends how far you want to go with it.

Leave a Comment