Add_action not working in required file of functions.php

The 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.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

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

Leave a Comment