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

查看:135
本文介绍了如何在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: http://#.com
Description: A plugin that is used for my javascript tests
Author: Ronny Kibet
Author URI: http://ronnykibet.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的钩子,如@brasofilo所提到的,它应该用来代替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天全站免登陆