問題描述

我建立了一個使用 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。