How do I add a simple jQuery script to WordPress?

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

    If you use wordpress child theme for add scripts to your theme, you should change the get_template_directory_uri function to get_stylesheet_directory_uri, for example :

    Parent Theme :

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

    Child Theme :

    add_action( 'wp_enqueue_scripts', 'add_my_script' );
    function add_my_script() {
        wp_register_script(
           'child-theme-script', 
           get_stylesheet_directory_uri() . '/js/your-script.js', 
           array('jquery') 
        );
    
        wp_enqueue_script('child-theme-script');
    }
    

    get_template_directory_uri : /your-site/wp-content/themes/parent-theme

    get_stylesheet_directory_uri : /your-site/wp-content/themes/child-theme

提交回复
热议问题