简体   繁体   English

在Wordpress插件中加载自定义JavaScript

[英]Loading custom javascript in a Wordpress plugin

OK, this is driving me nuts: 好的,这让我疯了:

I'm trying to build a simple Wordpress plugin, and I'm trying to make sure the js is separate from the php. 我正在尝试构建一个简单的Wordpress插件,我正在努力确保js与php分开。 I've gone through the codex, and various tutorials, but either they are all making assumptions, or I'm just an idiot because it's not working...Basically, I'm ultiamtely hoping to add some rows using ajax to a custom table when I add a post, but first of all I've just got to get this Hello World working on a Add Post page... 我已经完成了手抄本和各种教程,但要么他们都在做假设,要么我只是一个白痴,因为它不起作用......基本上,我最终希望使用ajax添加一些行来定制我添加帖子时的表格,但首先我要让这个Hello World在Add Post页面上运行...

Surely It's dead easy: 当然这很容易:

Here's the javascript in myplug/js/myplugin.js: 这是myplug / js / myplugin.js中的javascript:

jQuery(document).ready(function(){
    alert("dothis");
});

Here's the version that works in the plugin (but is bad): 这是插件中的版本(但很糟糕):

function admin_load_js(){
    echo '<script type="text/javascript" src="http://www.mysite.com/wp-content/plugins/myplugin/js/myplugin.js"></script>';
}
add_action('admin_head', 'admin_load_js');

This is marginally better, but doesn't work (jQuery not defined): 这稍微好一些,但不起作用(jQuery未定义):

function admin_load_js(){
    echo '<script type="text/javascript" src="http://www.mysite.com/wp-content/plugins/myplugin/js/myplugin.js"></script>';
}
add_action('admin_enqueue_scripts', 'admin_load_js');

And this is the way I think it should be done, but doesn't work at all just doesn't do anything: 这是我认为应该这样做的方式,但根本不起作用只是没有做任何事情:

function admin_load_js(){
 wp_register_script( 'custom_js', plugins_url( '/js/myplugin.js', __FILE__ ) );
}
add_action('admin_enqueue_scripts', 'admin_load_js');

Can someone please give me a clue here?? 有人可以在这里给我一个线索吗? Even Google isn't my friend at the moment. 即使谷歌目前也不是我的朋友。 Maybe because it's late, I don't know... 也许是因为已经晚了,我不知道......

Try this: 尝试这个:

function admin_load_js(){
    wp_enqueue_script( 'custom_js', plugins_url( '/js/myplugin.js', __FILE__ ), array('jquery') );
}
add_action('admin_enqueue_scripts', 'admin_load_js');

wp_register_script just registers the script. wp_register_script只是注册脚本。 You still need to load the script manually. 您仍需要手动加载脚本。

Or you could use wp_enqueue_script which does it all at the same time. 或者您可以使用wp_enqueue_script同时完成所有操作。 With wp_enqueue_script, you can specify dependencies (in this case 'jquery') so that they will be loaded before your script. 使用wp_enqueue_script,您可以指定依赖项(在本例中为“jquery”),以便在脚本之前加载它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM