Best place to load wp_ajax_the_ajax_hook action in plugin


I am building a shortcode plugin and I want to avoid loading unecessary code unless the shorcode is called in a page.

I am having trouble with the ajax functions. It seems I need to load everything very early in the plugin code, thus loading unecessary code for the whole site.

I am talking about the usual calls in adding ajax

add_action( 'wp_ajax_the_ajax_hook', 'testFunction' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'testFunction' ); 

and also the backend function needs to load.

function testFunction(){
        //do some server side thing with $POST
        echo 'this is a test function';

If I don’t load the add_action’s at my plugin “top” code I don’t get the ajax.js loaded
If I don’t load the testFunction at my plugin “top” code I get a call_user_func_array() expects parameter 1 to be a valid callback, function ‘testFunction’ not found or invalid function name

I have no problem loading the scripts “on demand” when shortcode is called, that is:

wp_enqueue_script( 'my-ajax-handle', FAU_PLUGIN_URL . 'js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

Hope someone has had this issue too… Thank you in advance

, Rodolfo Cristovao 7 years 2016-02-19T16:18:59-05:00 0 Answers 78 views 0

Leave an answer