Hi everyone! New dev here and I am having trouble making php variables available on the front-end (i.e. localizing variables) using `wp_localize_script()`. Here is the code from my project that is related to the problem:
/*** functions.php ***/
require get_stylesheet_directory() . '/admin.php';
function enqueue_front_end() {
wp_enqueue_script(
'custom_fetch_script',
get_template_directory_uri() . '/assets/js/front_end.js',
array( 'wp-api', 'wp-api-fetch' ),
'1.0.0',
true
);
wp_localize_script('custom_fetch_script', 'custom_fetch', array(
'root_url' => get_site_url(),
'action_url' => admin_url('add-to-cart-logic.php'),
'security' => wp_create_nonce('wc_store_api')
)
);
}
add_action('wp_enqueue_scripts', 'enqueue_front_end');
This is the setup recommended by AI, YouTube, Google and Stack Overflow. However, when I log the `custom_fetch` object to the console, this is what I see:
Uncaught ReferenceError: custom_fetch is not defined
I tried rearanging the functions in different ways to but that that didn't solve the problem either. According to the docs on wordpress.org, I also tried using the `wp_add_inline_script()` function like this:
require get_stylesheet_directory() . '/admin.php';
function enqueue_front_end() {
wp_enqueue_script(
'custom_fetch_script',
get_template_directory_uri() . '/assets/js/front_end.js',
array( 'wp-api', 'wp-api-fetch' ),
'1.0.0',
true
);
wp_add_inline_script(
'custom_fetch_script',
'const custom_fetch = ' . json_encode(array(
'ajaxurl' => admin_url('admin.php'),
'nonce' => wp_create_nonce('wc_store_api'),
'root_url' => get_site_url(),
)),
'before'
);
}
add_action('wp_enqueue_scripts', 'enqueue_front_end');
This to however did not solve the problem. Could anyone perhaps spot something I might be missing? If so, please let me know (If you need to see more code, don't hesitate to ask). Thanks in advance!
