我正在构建一个小的图库插件,如果图库是通过模板标签加载的,我只想将脚本/样式加载到页面上。当模板标记用于从主题中需要的任何位置调用帖子库时,可以使用帖子ID参数。
我知道如何在单个页面上执行此操作(我只需查找meta\\u键并将其与当前查看的帖子进行匹配),但检测主页(或任何其他页面)上是否存在图库更为困难。
因此,我们假设模板标记如下所示:
if ( function_exists( \'my_gallery\' ) )
echo my_gallery( \'100\' ); // gallery of image from post 100 will be shown
gallery函数如下所示(简化):function my_gallery( $post_id = \'\' ) {
// whole bunch of stuff in here which is returned
}
库的脚本和样式如下所示(简化):function my_gallery_scripts() {
wp_register_script( \'my-gallery-js\', MY_GALLERY_URL . \'js/my-gallery.js\', array( \'jquery\' ), \'1.0\', true );
wp_register_style( \'my-gallery-css\', MY_GALLERY_URL . \'css/my-gallery.css\', \'\', \'1.0\', \'screen\' );
// need to load these conditionally, but how?
wp_enqueue_style( \'my-gallery-js\' );
wp_enqueue_script( \'my-gallery-css\' );
}
add_action( \'wp_enqueue_scripts\', \'my_gallery_scripts\' );
我试过使用set_query_var
在…内my_gallery()
这样可以在$wp\\u查询中设置一个全局变量。 function my_gallery( $post_id = \'\' ) {
set_query_var( \'has_gallery\', true );
// whole bunch of stuff in here which is returned
}
但问题是我不能使用get_query_var
内部wp_enqueue_scripts
行动因此,我相信下面的内容对我来说非常理想,将has\\u gallery加载到$wp\\u查询对象中,我可以在每个页面上使用该对象(除非它不起作用)。
function my_gallery_scripts() {
wp_register_script( \'my-gallery-js\', MY_GALLERY_URL . \'js/my-gallery.js\', array( \'jquery\' ), \'1.0\', true );
wp_register_style( \'my-gallery-css\', MY_GALLERY_URL . \'css/my-gallery.css\', \'\', \'1.0\', \'screen\' );
// does not work
$has_gallery = get_query_var( \'has_gallery\' );
if ( $has_gallery ) {
wp_enqueue_style( \'my-gallery-js\' );
wp_enqueue_script( \'my-gallery-css\' );
}
}
add_action( \'wp_enqueue_scripts\', \'my_gallery_scripts\' );
是否有其他方法可以设置类似于set\\u query\\u var的全局选项,但可以在我的场景中使用?很明显,我想避免使用全局变量。我还尝试设置一个常量,但没有效果。