通过插件在管理头中添加脚本 [英] Adding script, via plugins, in the admin head

查看:71
本文介绍了通过插件在管理头中添加脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个 Wordpress 插件,我正在尝试将 javascript 添加到管理员头.我试过了,但无法做到,有人可以帮忙吗?波纹管是我想要的:

I've made a Wordpress plugin, and I'm trying to add javascript to the admin head. I've tried but couldn't managed to do it, could anyone help? Bellow is what I was going with:

  function __construct() {        
    add_action('wp_head', 'wpb_hook_javascript');
  }

function wpb_hook_javascript() {
?>
    <script>
      // javscript code 
    </script>
<?php

}

推荐答案

您可以通过 'admin_head',像这样:

You can add a function (preferably in the root of your plugin directory) via 'admin_head', like so:

function my_custom_admin_script() {

    // get the current files folder name.
    $my_plugin_name = trim( dirname( plugin_basename( __FILE__ ) ), '/' );

    // get the plugin directory and add folder name.
    $my_plugin_directory = plugins_url() . '/' . $my_plugin_name;

    // enqueue script.
    // See https://developer.wordpress.org/reference/functions/wp_enqueue_script/
    wp_enqueue_script( 'my-script-name-reference', $my_plugin_directory . '/js/my-script.js', array( 'jquery' ), filemtime( $my_plugin_directory . '/js/my-script.js' ), true );

};
add_action( 'admin_head', 'my_custom_admin_script' );

/js/script.js 更改为您的脚本在插件结构中的位置.

Change /js/script.js to where you script is in your plugin structure.

这将在 WordPress 管理屏幕上加载脚本 - 但不是块编辑器.如果您想在块编辑器中附加脚本,您应该将 admin_head 替换为 enqueue_block_editor_assets - 查看文档.

This will then load the script on WordPress Admin screens - but not the Block Editor. If you want to attach a script in the block editor you should replace admin_head with enqueue_block_editor_assets - see the docs.

这篇关于通过插件在管理头中添加脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆