Add_action not working in required file of functions.php

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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");


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x