@bosco,thanx的评论。。。我误解了@Alen想要实现的目标(theglobal $post
在问题中包含的代码中)。
如果我现在的理解是正确的,那么下面应该可以做到(虽然有点难看)。它通过钩住wp_print_styles
within 处理短代码的函数。
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: 如果你能想象
[my_shortcode]
在一篇给定的帖子中被多次使用,最好在上面添加逻辑,以检查是否已经为给定的帖子ID输出了CSS。我将此作为“读者练习”:-)