@bosco, thanx for the comment...I misunderstood what @Alen was trying to accomplish (the global $post
in the code included in the question threw me off).
If my understanding is now correct, the following should do the trick (altho, it's a bit ugly). It works by hooking into wp_print_styles
within the function that processes the shortcode.
add_shortcode ('my_shortcode', 'my_shortcode') ;
function
my_shortcode ($atts)
{
$defaults = array (
'id' => '',
// other atts for the shortcode
) ;
$atts = shortcode_atts ($defaults, $atts) ;
if (!empty ($atts['id'])) {
global $my_shortcode_css ;
// grab the CSS from the post whose ID was passed in the 'id' attribute of
// my_shortcode, e.g., [my_shortcode id='123']
// and store it in a global
$my_shortcode_css = get_post_meta ($atts['id'], 'append_css', true) ;
// no need to hook into wp_print_styles IF we don't have any CSS to output
if (!empty ($my_shortcode_css)) {
// hook into wp_print_styles with an anonymous func
add_action ('wp_print_styles', function () {
global $my_shortcode_css ;
if (empty ($my_shortcode_css)) {
return ;
}
echo <<<EOF
<style type='text/css'>
$my_shortcode_css
</style>
EOF;
// clean up, since we no longer need this global
unset ($my_shortcode_css) ;
}) ;
}
}
// insert code to produce the output of the shortcode
$output = ... ;
return ($output) ;
}
Note: If you can conceive of [my_shortcode]
being used more than once within a given post, it would probably be a good idea to add logic to the above to check whether CSS has already been output for a given post ID. I'll leave that as an "exercise for the reader" :-)
add_action
code? If it's not in thefunctions.php
inside the active theme you should transfer it there.