答案 0 :(得分:58)
使用admin_enqueue_scripts
操作和wp_enqueue_script
方法将自定义脚本添加到管理界面。
这假设您的插件文件夹中有myscript.js
。相应地改变。 my_custom_script
句柄对于您的模块和脚本应该是唯一的。
function my_enqueue($hook) {
// Only add to the edit.php admin page.
// See WP docs.
if ('edit.php' !== $hook) {
return;
}
wp_enqueue_script('my_custom_script', plugin_dir_url(__FILE__) . '/myscript.js');
}
add_action('admin_enqueue_scripts', 'my_enqueue');
答案 1 :(得分:42)
您的functions.php文件有一个片段:
function custom_admin_js() {
$url = get_bloginfo('template_directory') . '/js/wp-admin.js';
echo '"<script type="text/javascript" src="'. $url . '"></script>"';
}
add_action('admin_footer', 'custom_admin_js');
在Wordpress 3.2.1上运行良好。
答案 2 :(得分:19)
答案 3 :(得分:3)
U=U'; V=V';
plot((V((length(U)+1)/2,:)),A((length(U)+1)/2,:));
plot((U((length(U)+1)/2,:)),B((length(U)+1)/2,:));
和admin_enqueue_scripts
是将javascript文件添加到信息中心的首选方式。
wp_enqueue_script
如果您想使用PHP函数输出javascript,// I'm using an anonymous function for brevity.
add_action( 'admin_enqueue_scripts', function() {
wp_enqueue_script( 'handle', plugin_dir_url( __FILE__ ) . '/script.js' );
} );
似乎不起作用。相反,您可以使用wp_add_inline_script
直接回显脚本,包括脚本标记本身。只需确保将优先级设置为高,以便在任何所需的库之后加载,例如admin_print_scripts
。
jQuery
答案 4 :(得分:0)
如果想花哨的地方并过滤是否要加载文件的位置,最好使用get_current_screen
。
function myproject_admin_enqueue() {
$screen = get_current_screen();
// load on the NEW and EDIT screens of all post types
if ( 'post' === $screen->base ) {
wp_enqueue_script('my_custom_script', plugin_dir_url( __FILE__ ) . 'all-admin.js');
}
// load on the NEW and EDIT screens of one post type
if ( 'post' === $screen->base && 'myposttype' === $screen->post_type ) {
wp_enqueue_script('my_custom_script', plugin_dir_url( __FILE__ ) . 'mypostype-admin.js');
}
// load only when adding a NEW post, not when editing an existing one.
if ( 'post' === $screen->base && 'add' === $screen->action ) {
wp_enqueue_script('my_custom_script', plugin_dir_url( __FILE__ ) . 'new-admin.js');
}
}
add_action('admin_enqueue_scripts', 'myproject_admin_enqueue');
答案 5 :(得分:0)
直接在代码中添加 wp_enqueue_script 不会在新版本的Wordpress(5.0以上)中包含该脚本。 更好的方法是先向wp_register_script注册脚本以创建一个句柄,然后使该句柄排队。
function custom_script_in_admin($hook) {
if ('edit.php' !== $hook) {
return;
}
wp_register_script( 'custom_handle_name',plugin_dir_url( __FILE__ ) . '/script.js', '',true );
wp_enqueue_script('custom_handle_name');
}
add_action('admin_enqueue_scripts', 'custom_script_in_admin');
答案 6 :(得分:0)
不知何故,接受的答案对我不起作用。这是我在答案中没有找到的另一个解决方案,这就是为我所做的,WP 5.x,为我的后端添加了一些 css 和 js...
function suedsicht_theme_add_editor_assets() {
wp_enqueue_style( 'custom-gutenberg-stylesheet', get_template_directory_uri() . '/css/custom-editor-style.css', array(), wp_get_theme()->get( 'Version' ), 'all' );
wp_enqueue_script('suedsicht-admin-js', get_template_directory_uri() . '/js/admin.js');
}
add_action( 'enqueue_block_editor_assets', 'suedsicht_theme_add_editor_assets' );