79656183

Date: 2025-06-06 16:12:00
Score: 0.5
Natty:
Report link

I found this blog post and was able to adapt my code and was able to pass the ajax url to the front end script. see below:

function add_my_script(){

$ajax_url = [
    'ajax_url' => admin_url( 'admin-ajax.php' ) 
];

$my_ajax_object = sprintf('window.%s = %s', 'my_ajax_object',json_encode($ajax_url));
    
wp_enqueue_script( 'modTest', get_stylesheet_directory_uri() . '/bsd-js.js', array ( 'jquery' ), false, true);
addModuleTag('modTest');
wp_add_inline_script('modTest',$my_ajax_object,'before');
wp_enqueue_script_module('modTest2',get_stylesheet_directory_uri() .'/Modules/testMod.js');
}

function addModuleTag($scriptHandle){
add_filter('script_loader_tag', 
function($tag, $handle,$src) use ($scriptHandle) {
    // Check if the script handle matches the one we want to modify
    if ($handle === $scriptHandle) {
        // Add the type="module" attribute to the script tag
            return str_replace(' src', ' type="module" src', $tag);
    }
    }, 10, 3);
}

The above code will result in being able to use my_ajax_object.ajax_url in the javascript module file(s). The addModuleTag function when the matching script handle is found will change the <script> tag type of the bsd-js.js file I enqueued to a module. wp_add_inline_script will send my ajax url to a script tag in the js file so it can be used. Next item to look into is how to get jquery also into the module

Reasons:
  • Blacklisted phrase (1): this blog
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: ProfoundHypnotic