問題描述

我一直在嘗試載入 WordPress 小工具的指令碼和樣式,具有以下條件…

  1. 指令碼必須在 HEAD 中載入 (否則它們會中斷) 。

  2. 指令碼必須在視窗小工具實際顯示時才載入 (它們相當沉重) 。

我做了很多的搜尋,這似乎是一個常見的 (未解決的) 問題… 但我希望有人在這裡成功實施了一個解決方法。

這是迄今為止最好的

以下是向側邊欄列印文字的簡單小工具。它有條件地成功地載入 jQuery(當實際顯示小工具時)… 雖然只有在頁尾中! (注意:它是 may also only work on WordPress 3.3,儘管 this hack 可能會提供向後相容性) 。

class BasicWidget extends WP_Widget
{

    function __construct() {
        parent::__construct(__CLASS__, 'BasicWidget', array(
            'classname' => __CLASS__,
            'description' => "This is a basic widget template that outputs text to the sidebar"
        ));
    }

  function form($instance) {
    $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
    $title = $instance['title'];
?>
  <p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></label></p>
<?php
  }

  function update($new_instance, $old_instance) {
    $instance = $old_instance;
    $instance['title'] = $new_instance['title'];
    return $instance;
  }

  function widget($args, $instance) {

    extract($args, EXTR_SKIP);

    echo $before_widget;
    $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);

    if (!empty($title))
      echo $before_title . $title . $after_title;;

    echo "<h1>This is a basic widget!</h1>";

    echo $after_widget;

        // if we're echoing out content, enqueue jquery.

        if (!empty($after_widget)) {
            wp_enqueue_script('jquery');
        }
    }
}
add_action( 'widgets_init', create_function('', 'return register_widget("BasicWidget");') );

WordPress 似乎開始處理小工具,現在為了排隊 (甚至取消註冊先前已經排隊的內容) 已經太遲了。

任何想法都將不勝感激!

標記。

最佳解決方案

WordPress 作為一個很好的函式 is_active_widget,您可以在__construct 中使用,並測試該視窗小工具是否存在於當前頁面中,並根據該示例新增您的指令碼/樣式:

function __construct() {
    parent::__construct(__CLASS__, 'BasicWidget', array(
        'classname' => __CLASS__,
        'description' => "This is a basic widget template that outputs text to the sidebar"
    ));
     if ( is_active_widget(false, false, $this->id_base) )
        add_action( 'wp_head', array(&$this, 'add_styles_and_scripts') );
}

function add_styles_and_scripts(){
    //since its wp_head you need to echo out your style link:
    echo '<link rel="stylesheet" href="http://example.com/css/style.css" type="text/css" />';
    //as for javascript it can be included using wp_enqueue_script and set the footer parameter to true:
    wp_enqueue_script( 'widget_script','http://example.com/js/script.js',array(),'',true );
}

參考文獻

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