問題描述

我創建了一個使用 jquery 插件的窗口小工具,我使用 is_active_widget 來排列腳本,它的工作正常,但即使在不顯示此窗口小工具的頁面上也包含該腳本。那麼如果這個小工具正在顯示,那麼只有入門腳本的方法呢?

提前致謝。

最佳解決方案

您應該可以調用 wp_enqueue_script()作為您的 Widget 輸出的一部分。

Edit

Quick-and-dirty,使用 bare-bones Widgets API 類示例:

<?php
class wpse48337_Widget extends WP_Widget {

    public function __construct() {
        // widget actual processes
    }

    public function form( $instance ) {
        // outputs the options form on admin
    }

    public function update( $new_instance, $old_instance ) {
        // processes widget options to be saved
    }

    public function widget( $args, $instance ) {
        // outputs the content of the widget
    }

}
register_widget( 'wpse48337_Widget' );
?>

在您的 Widget 的輸出內,即在 public function widget()內部內聯添加 wp_enqueue_script()調用:

<?php    
    public function widget( $args, $instance ) {
        // outputs the content of the widget

    // Enqueue a script needed for
    // the Widget's output
    wp_enqueue_script( 'jquery-pluginname', $path, $deps );

    // Rest of widget output goes here...
    }
?>

次佳解決方案

如果腳本需要進入<head> 部分:

class Your_Widget extends WP_Widget{

  protected static $did_script = false;

  function __construct(){

    // parent::__construct() ...

    add_action('wp_enqueue_scripts', array($this, 'scripts'));

  }

  function scripts(){

    if(!self::$did_script && is_active_widget(false, false, $this->id_base, true)){
      wp_enqueue_script('your-script');
      self::$did_script = true;
    }           

  }


}

否則,Chip Bennett 的解決方案將用於在頁腳中排隊。

$did_script 靜態變量不是必需的,我使用它只是為了避免進一步不必要的調用 wp_enqueue_script 如果頁面上有多個窗口小工具實例…

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。