Understanding WordPress child theme custom JS loading

This is the proper way to load a custom javascript in your child theme, wp_localize_script is only necessary if you need to exchange data between JS and PHP (Client and server).

function assets() {
     wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], '1.0', false);
     wp_enqueue_script('ajax_filter');
     wp_localize_script( 'ajax_filter', 'mdu', array(
         'nonce'    => wp_create_nonce( 'mdu' ),
         'ajax_url' => admin_url( 'admin-ajax.php' )
     ));
}
add_action('wp_enqueue_scripts', 'assets');

So my issue as noticed by @KAGG was that i was loading this JS from another fileā€¦

Thanks for his help !

Matth

Leave a Comment