如何在 Wordpress 插件中加载 Javascript [英] how to load Javascript in Wordpress Plugin

查看:28
本文介绍了如何在 Wordpress 插件中加载 Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何将这个 javascript 文件包含到我的 wordpress 插件中.我已经尝试了所有 wp_enqeue_script() 方法,但没有任何反应.

Can someone show me how to include this javascript file into my wordpress plugin. I have tried all the wp_enqeue_script() methods but nothing happens.

好的,这是我的示例插件代码,带有解释我想要什么的注释.

ok here is my example plugin code with comments explaining what I would like.

<?php
/*
Plugin Name: Ava Test
Plugin URI: http://#.com
Description: A plugin that is used for my javascript tests
Author: Ronny Kibet
Author URI: http://ronnykibet.com
version: 1.001
*/

include(popup.js); 
/*when I include it this way, it works fine, but gives an error when I activate the plugin
'plugin generated 453 characters ...'
*/

function popup() {
$src = plugins_url('popup.js', __FILE__);
wp_register_script( 'popup', $src );
wp_enqueue_script( 'popup' );
}
/*
when I included it this way, plugin is activated but nothing happens.
*/
?>

这是 popup.js

this is the popup.js

<script type="text/javascript">

function popup(){


alert('hello there this is a test popup')

}
</script>
<body onload="popup()">
</body>

那么有人知道如何调用这个脚本才能在 wordpress 插件中正常工作吗?

So does anybody know how to call this script to work correctly in wordpress plugin?

推荐答案

你需要指定加载的时间,试试这个.

You need to specify when the load should happen, try this.

<?php
/*
Plugin Name: Ava Test
Plugin URI: https://matsio.com
Description: A plugin that is used for my javascript tests
Author: Ronny Kibet
Author URI: https://matsio.com
version: 1.001
*/

add_action('wp_enqueue_scripts','ava_test_init');

function ava_test_init() {
    wp_enqueue_script( 'ava-test-js', plugins_url( '/js/ava_test_.js', __FILE__ ));
}

另外,你的 JS 中有错误,但我在一些答案中看到了正确的版本,希望对你有帮助

Also, there are errors in your JS, but I have seen the correct version in some answers, hope this helps

更新:有一个叫做 wp_enqueue_scripts 的钩子,正如@brasofolo 提到的,它应该用来代替 init 来加载脚本.

Update : There is a hook called wp_enqueue_scripts, as mentioned by @brasofilo which should be used in lieu of init for loading scripts.

这篇关于如何在 Wordpress 插件中加载 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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