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'; die(); }
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
has_shortcode()
but I'm not sure reliable that will be when adding hooks since you need actual$post_content
to test against.add_action
and thetestFunction
if the shortcode exists on the page?