Search code examples
javascriptwordpressparent-childchild-theming

Adding a JS file in a Wordpress block child theme


I am creating a block child theme of Wordpress, I need to attach my own CSS sheet and JS file. As recommended, I queued both files in functions.php with:


//dodanie własnych css i js
add_action( 'wp_enqueue_scripts', 'child_enqueue_assets' );

function child_enqueue_assets() {
    //css
    wp_enqueue_style( 'style', get_stylesheet_uri() );
    //js
    wp_enqueue_script( 'script', get_template_directory_uri() . '/script.js', array( 'jquery' ),'',true );
}

add_action( 'admin_init', 'child_editor_styles' );

function child_editor_styles() {
    add_editor_style( [
        get_stylesheet_uri()
    ] );
}

Why is my console browser showing error 404 - JS file not found in parent theme path and not child theme (get_template_directory_uri (). '/Script.js')? I put the JS file in the child theme and hence I want it to be read, not from the parent theme location. The previously queued patch CSS file is read from the child theme. What am I doing wrong with the JS file?


Solution

  • The get_template_directory_uri() will always return the current parent theme url.

    To get the child theme URI instead, you should be using get_stylesheet_directory_uri()

    In your code replace the following line:

    wp_enqueue_script( 'script', get_template_directory_uri() . '/script.js', array( 'jquery' ),'',true );
    

    with

    wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/script.js', array( 'jquery' ),'',true );
    

    I hope this will help you.