0

To include a CSS file and a JS file I added to functions.php:

function my_theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}

function my_theme_enqueue_scripts() {
    wp_enqueue_script( 'behavior', get_script_directory_uri() . '/behavior.js', array(), null, true );
}

add_action( 'wp_enqueue_style', 'my_theme_enqueue_styles' );
add_action( 'wp_enqueue_script', 'my_theme_enqueue_scripts' );

After doing so, I saved and closed the editor, went back to the same directory of functions.php (this is the child theme's directory), ad created a new file, behavior.js.

In behavior.js, I added, just for testing:

alert('Hi');

I saved, went back to my site, and did full refresh, but no alert appears. Why is that?

1 Answer 1

2

You're using the wrong hook. wp_enqueue_scripts is the correct hook for both:

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );

But since they're the same hook you can just enqueue both files in the same callback:

function my_theme_enqueue_assets() {
    wp_enqueue_style( 'parent-style', get_parent_theme_file_uri( 'style.css' ) );
    wp_enqueue_script( 'behavior', get_theme_file_uri( 'behavior.js' ), array(), null, true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_assets' );

I've also used the newer get_parent_theme_file_uri() and get_theme_file_uri() functions to get the file URLs. get_parent_theme_file_uri() will get the URI for the given file inside the parent theme only, while get_theme_file_uri() will get the file from the current theme, and if it's a child theme it will fall back to the parent theme if the file doesn't exist in the child theme.

Note that these still need the path to the file inside the theme if they're in a folder, eg. get_theme_file_uri( 'path/to/file.js' );

8
  • This made my site show WSOD...
    – user87795
    Commented Sep 12, 2017 at 2:07
  • Well not WSOD. CTRL+U shows some little bit HTML, but the CSS isn't loaded at all. I just see a white blank page. No HTML by my page builder (Elementor) is loaded so it seems adding a JS make my page builder not to load.
    – user87795
    Commented Sep 12, 2017 at 2:50
  • get_script_directory_uri() isn't a function, you're getting an error because my_theme_enqueue_scripts is correctly hooked, but contains this error. Commented Sep 12, 2017 at 2:52
  • 1
    Your style function works because wp_enqueue_style is using get_template_directory_uri, and it wasn't broken before because my_theme_enqueue_scripts() wasn't running at all. I'd didn't twig that you were in a child theme, so I'll update my answer. Commented Sep 12, 2017 at 3:07
  • 1
    I've updated my answer with a better solution. Commented Sep 12, 2017 at 3:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.