1

I'm working on a plugin that uses thickbox and media-upload to set some images. Neither will load using this code:

  function add_my_files() {
        echo 'happy happy happy';
        wp_register_style( 'adminstyles', plugins_url('/css/slider.css', __FILE__));
        wp_enqueue_style( 'adminstyles' );
        wp_enqueue_style('thickbox');

        wp_enqueue_script('media-upload');
        wp_enqueue_script('thickbox');

        wp_register_script('hdjs',plugins_url('/js/slider.js', __FILE__),array('media-upload','thickbox'),'',true);
        wp_enqueue_script('hdjs');
    }

add_action( 'admin_init', 'add_my_files' );

my css and js files load but not thickbox and media-upload.

Thanks

4

1 回答 1

1

将资产文件包含在 WP 中的正确挂钩是admin_enqueue_scripts

注意:我建议您也使用get_current_screen(参见is_my_admin_screen()下面的定义)在您实际需要时仅包含您的 js/css 文件。

add_action('admin_enqueue_scripts', 'add_my_files');

function add_my_files()
{
    /*
     * a good WP citizen only loads
     * their javascript/css where it is needed
     */
    if ( ! is_my_admin_screen()) // defined below
        return;

    wp_register_style('adminstyles', plugins_url('/css/slider.css', __FILE__));
    wp_enqueue_style('adminstyles');
    wp_enqueue_style('thickbox');

    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');

    wp_register_script('hdjs', plugins_url('/js/slider.js', __FILE__), array('media-upload', 'thickbox'), '', true);
    wp_enqueue_script('hdjs');
}

function is_my_admin_screen()
{
    $screen = get_current_screen();

    if (is_object($screen) && $screen->id == 'my_plugin_page_id') // var_dump($screen->id); find your own id
        return true;
    else
        return false;
}

参考:http ://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts 参考:http: //codex.wordpress.org/Function_Reference/get_current_screen


除了希望你使用一个类来包装你的所有插件,否则你会遇到比这更糟糕的问题。

请反馈。我对这个问题很感兴趣,因为 WP 插件把食物和啤酒放在了我的桌子上。

于 2012-12-27T22:54:22.783 回答