【问题标题】:WP load scripts if template has shortcode如果模板有短代码,则 WP 加载脚本
【发布时间】:2017-04-06 15:56:42
【问题描述】:

我有一个插件,它有很多 css 主题文件。当然,我不想加载所有这些,只加载一个。这取决于配置。对于帖子,我使用 has_shortcode 函数,但是如何使用使用 do_shortcode 函数的模板来做同样的事情。

注意:

我找到了一个很好的解决方案,我使用

$this->loader->add_action( 'init', $plugin_public, 'register_scripts');
$this->loader->add_action( 'wp_footer', $plugin_public, 'print_scripts');

在短代码句柄中,我将全局变量设置为 true

global $imagelink_plugin_shortcode_used;
$imagelink_plugin_shortcode_used = true;

如果我的全局变量为 true

print_scripts 函数会添加我的脚本
public function print_scripts() {
   global $imagelink_plugin_shortcode_used;

   if ( ! $imagelink_plugin_shortcode_used )
       return;

   wp_print_scripts($this->plugin_name . '-imagelinks');
}

感谢您的回答。

【问题讨论】:

  • 您能否提供更多关于您正在使用的插件的信息,并更清楚地说明您要做什么?
  • 如果它是您编写的插件,您可以将脚本放入短代码函数中

标签: wordpress plugins styles shortcode


【解决方案1】:

除了使用 has_shortcode 函数,您可以做的是在呈现该简码时注册这些文件并将其排入队列。

首先,使用wp_register_script 注册您的css 文件。确保将其连接到 wp_enqueue_scripts

现在,在您的简码函数中,将文件排入队列。

wp_enqueue_style('theme-css')

使用这种方式,您可以在任何您想要的地方使用简码,并且只有当简码出现在页面上时才会加载脚本,无论它是在内容还是模板上。

【讨论】:

  • 这将始终将您的脚本加载到页脚中,无论 in_footer 变量如何。如果我们需要将脚本挂接到头部怎么办?
猜你喜欢
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 2018-02-27
  • 2017-10-20
相关资源
最近更新 更多