如何将jquery添加到wordpress插件

时间:2014-12-26 13:40:08

标签: javascript php jquery wordpress

对于wordpress专家来说,这可能是一个非常简单的问题。我是wordpress的新手,我在使用jquery时遇到问题。已经包含了jquery库,因为你可以看到它是firebug

我不知道我在这里缺少什么。

这是我的代码..

add_action( 'wp_enqueue_scripts', array( $this, 'jsscript' ) );


function jsscript() {   
    ?>
    <script type="text/javascript">
        $(document).ready(function(){
            alert('here!');
        });
    </script>
    <?php
    }

jsscript已经在firebug上,但它不起作用。我在firebug中收到此错误消息。

ReferenceError: $ is not defined
$(document).ready(function(){

我在某处读到包含另一个jquery库并不是一个好主意,并且不再加载它是有意义的。

我希望有人可以帮助我。

提前致谢。

4 个答案:

答案 0 :(得分:2)

您应该将它添加到插件目录中的外部文件中,而不是随意输出您的脚本,然后将该文件包含在jQuery中作为依赖项

wp_enqueue_script(
      'jsscript', 
      plugin_dir_path( __FILE__ ) . '/jsscript.js', 
      array( 'jquery' )
);

您现在遇到的问题是,无法保证在jQuery之后输出脚本,实际上现在可以保证您之间输出的脚本标记PHP标签被插入到它应该去的地方。

答案 1 :(得分:2)

为了避免其他js库之间的冲突,在wordpress中不存在全局$,而是使用jQuery

Read this for more info

例如:

jQuery(document).ready(function () {
    alert('here!');
});

答案 2 :(得分:1)

将此代码放入您的functions.php文件

function yourfunction_name() {
global $wp_scripts;
    wp_register_script('jqury_lib', "//code.jquery.com/jquery-1.11.2.min.js", array(), null);
}
add_action( 'wp_enqueue_scripts', 'yourfunction_name' );

答案 3 :(得分:1)

主题:

wp_enqueue_script(
        'custom-script',
        get_stylesheet_directory_uri() . '/js/custom_script.js',
        array( 'jquery' )
    );

对于插件:

wp_enqueue_script(
        'newscript',
        plugins_url( '/js/newscript.js' , __FILE__ ),
        array( 'scriptaculous' )
    );