如何将我的 JQuery 脚本添加到单个 wordpress 页面中?

问题描述:

我想将我的 JQuery 脚本添加到单个 Wordpress 页面中,但我不知道如何添加.我想注入的脚本示例:

I want to add my JQuery script into single Wordpress page, but I dont know how. Example of script I'd like to inject:

<script type="text/javascript">
    $(document).ready(function() {
        $("html, body").animate({ scrollTop: $(window).height() }, 600);

        return false;
    });
</script>

当注入纯 HTML 时,此代码工作正常,但我如何为 Wordpress 执行相同的操作?

This code works fine when injected in plain HTML, but how can I do the same for Wordpress?

你有几个选择,你上面创建的函数会将它添加到所有页面(你注册了脚本但没有实际调用它,这就是为什么它的不工作.请参阅下面的更正).

you have a couple of options, the function you created above will add it to all pages (you were registering the script but not actually calling it, thats why its not working. see correction below).

如果你愿意,你可以简单地将 wp_enqueue_script() 函数放在你的模板下面(没有添加动作和 custom() 函数

If you want you can simply place the wp_enqueue_script() function below in your template (without add action and the custom() function

或者直接将其写入模板文件(关于这是否是可接受的编码实践的争论很多,但它有效)

or directly write it into the template file (lots of arguments about whether this is acceptable coding practice, but it works)

或 require_once/include_once 文件以正确的顺序(您正在使用 document.ready,因此您可以在页眉下方的任何位置执行此操作(如果您已经在页眉中加载了 jquery,如果在页脚中,则必须在页脚下方)) 同样的规则适用于直接写入文件.

or require_once / include_once the file in the correct sequence (you are using document.ready so you can do this anywhere below the header (if you already have jquery loaded in the header, if in the footer, must be below the footer) same rules apply for directly writing into the file.

 function custom() { 

 wp_enqueue_script('jquery'); 
 wp_enqueue_script('add-custom-js' , get_template_directory_uri() . '/js/custom.js' , array('jquery'),'',true ); 
 } 
 add_action('wp_enqueue_scripts' . 'custom' );

  • WP 还使用非冲突 jquery,因此您需要使用 jQuery 而不是 $ 的简写形式.如果你用谷歌搜索,有几种使用速记的替代方法.