dongshao6591 2017-12-10 09:13
浏览 99
已采纳

通过插件在管理页面上加载自定义js文件

I'm new to the world of Wordpress and I just started developing my first plugin. When it's activated it should load one javascript file to wp-admin/post-new.php (Add new post) page.

Here is how I tried to do this:

Plugin

class WP_Blog_Customizer{
    function __construct() {
        add_action( 'wp_enqueue_scripts', array($this, 'load_dependencies') ); 
        register_activation_hook( __FILE__, array( $this, 'wpa_install' ) );
        register_deactivation_hook( __FILE__, array( $this, 'wpa_uninstall' ) );
    }
    public function load_dependencies(){
        wp_enqueue_script('blog-customizer', plugins_url('js/blog-customizer.js', __FILE__),array('jquery'),'1.0.0', true);
    }
}
new WP_Blog_Customizer();

wp-admin/post-new.php

if(is_plugin_active( 'blog-customizer/blog-customizer.php' )){
        $plugin = new WP_Blog_Customizer();
}

Shouldn't this add_action( 'wp_enqueue_scripts', array($this, 'load_dependencies') ); from the __construct of my plugin class include this js file?

Note

This js file is located under the js folder in my plugin's folder, so the path is correct.

Can anyone tell me why this is not working, and how to make it work?

  • 写回答

1条回答 默认 最新

  • doutiaosu2310 2017-12-10 12:48
    关注

    For loading scripts in admin side we have to use admin_enqueue_scripts hook. So something like this should do the job:

    class WP_Blog_Customizer{
        function __construct() {
            add_action( 'admin_enqueue_scripts', array($this, 'load_dependencies') ); 
            //...other constructor things
        }
        public function load_dependencies( $hook ){
            if ( $hook == 'post-new.php' ) { // for loading script also on post edit screen use ( $hook == 'post-new.php' || $hook == 'post.php' )
                wp_enqueue_script('blog-customizer', plugins_url('js/blog-customizer.js', __FILE__),array('jquery'),'1.0.0', true);
            }
        }
    }
    new WP_Blog_Customizer();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了