您可以预先检查帖子内容中是否存在短代码,如果找到,则将脚本排入标题中。
但是,您还必须回退到将其添加到页脚中,因为短代码可能会从其他地方运行(例如,在小部件、模板或编程方式中)
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 ...
}