Add_action not working in required file of functions.php
-
20-05-2021 - |
Question
I am trying to separate a part of my code from the functions.php file to make it easier to understand and maintain. So I want to put all my "ajax" related code in a different PHP file.
Here is the require in my functions.php file:
require_once( __DIR__ . '/includes/ajax.php');
And here is some of the content of the ajax.php file:
function theme_enqueue_ajax(){
wp_localize_script( 'myJSScript', 'ajaxUrl', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( "wp_enqueue_scripts", "theme_enqueue_ajax");
If I put the code from ajax.php directly in my functions.php file, everything works fine, but once I move it to ajax.php the ajaxUrl variable doesnt exist anymnore.
Solution
Of course there can be many reasons, but if you require ajax.php
in functions.php above the hook with wp_enqueue_script( 'myJSScript' ...);
- it will not work.
wp_localize_script()
Works only if the script has already been added.
function theme_enqueue_ajax(){
//try to add wp_enqueue_script( 'myJSScript' ...); here
wp_localize_script( 'myJSScript', 'ajaxUrl', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( "wp_enqueue_scripts", "theme_enqueue_ajax");
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange