Newcomer needs help properly enqueueing a script.

Could someone help me to enqueue a script for an accordion?
I've read the WordPress Codex on registering and enqueueing scripts and tried just about everything but I need outside help.

My situation:
Theme: Twentyseventeen-child theme on WordPress 4.7
File: accordion.js, stored as one of only 3 files in the child theme folder (along with style.css and functions.php)
I've registered the script.
I've enqueued the script.
I've done this(the above) in the functions.php file
When I load my page and look at the console + inspect elements, I see that there is no mention of accordion.js file, so I believe it isn't loading.

Could someone tell me what I've done wrong?

This is how I attempted to call the function.

function accordion() {
	wp_register_script( 'accordion', get_stylesheet_directory_uri() . '/accordion.js', array( 'jquery' ) );
	wp_enqueue_script( 'accordion', get_stylesheet_directory_uri() . '/accordion.js', array( 'accordion', 'jquery' ), '1.0', true );
}

add_action( 'wp_enqueue_scripts', 'twentyseventeen_child_theme_add_accordion' );

Here is the code for the accordion:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    }
}

Could someone steer me in the right direction?

  • Predrag Dubajic

    Hey John,

    Hope you're doing well today :slight_smile:

    There are couple of things wrong here that are causing the file not to load.
    #1 - Function name is not same as in add_action, replace accordion with twentyseventeen_child_theme_add_accordion to take care of this.
    #2 - Accordion name to load script seems to be taken already so that should be changed as well.
    To fix #1 and #2 try using this code in your functions.php:

    function twentyseventeen_child_theme_add_accordion() {
    	wp_register_script( 'accordion-child', get_stylesheet_directory_uri() . '/accordion.js', array( 'jquery' ) );
    	wp_enqueue_script( 'accordion-child', get_stylesheet_directory_uri() . '/accordion.js', array( 'accordion', 'jquery' ), '1.0', true );
    }
    
    add_action( 'wp_enqueue_scripts', 'twentyseventeen_child_theme_add_accordion' );

    And #3 - When I try to access the file itself by going to yourdomain.com/wp-content/themes/twentyseventeen-child/accordion.js the file is not found that location.
    Try moving the file to root folder of your child theme or change the path to correct one when enqueuing the script.

    Let us know how it goes after these changes :slight_smile:

    Best regards,
    Predrag

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.