How do I add a simple jQuery script to WordPress?

后端 未结 18 1733
心在旅途
心在旅途 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:48

    **#Method 1:**Try to put your jquery code in a separate js file.

    Now register that script in functions.php file.

    function add_my_script() {
        wp_enqueue_script(
          'custom-script', get_template_directory_uri() . '/js/your-script-name.js', 
            array('jquery') 
        );
    }
    add_action( 'wp_enqueue_scripts', 'add_my_script' );
    

    Now you are done.

    Registering script in functions has it benefits as it comes in section when page loads thus it is a part of header.php always. So you don't have to repeat your code each time you write a new html content.

    #Method 2: put the script code inside the page body under

提交回复
热议问题