How do I add a simple jQuery script to WordPress?

后端 未结 18 1957
心在旅途
心在旅途 2020-11-22 16:53

I read the Codex and a few blog posts about using jQuery in WordPress, and its very frustrating. I\'ve got as far as loading jQuery in functions.php file, but a

18条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 17:55

    Do you only need to load jquery?

    1) Like the other guides say, register your script in your functions.php file like so:

    // register scripts
    if (!is_admin()) {
        // here is an example of loading a custom script in a /scripts/ folder in your theme:
        wp_register_script('sandbox.common', get_bloginfo('template_url').'/scripts/common.js', array('jquery'), '1.0', true);
        // enqueue these scripts everywhere
        wp_enqueue_script('jquery');
        wp_enqueue_script('sandbox.common');
    }
    

    2) Notice that we don't need to register jQuery because it's already in the core. Make sure wp_footer() is called in your footer.php and wp_head() is called in your header.php (this is where it will output the script tag), and jQuery will load on every page. When you enqueue jQuery with WordPress it will be in "no conflict" mode, so you have to use jQuery instead of $. You can deregister jQuery if you want and re-register your own by doing wp_deregister_script('jquery').

提交回复
热议问题