I'm using ajax in a plugin for a front-end form.
But it only works if I place the add_action("wp_ajax_..."
in the plugin loader.
I would like to register the call in another file.
I have tried:
function my_plugin_init() {
if ( ! is_admin() ) {
require( dirname( __FILE__ ) . '/inc/my-plugin-functions.php' );
}
}
//add_action( 'wp_loaded', 'my_plugin_init' );
add_action( 'init', 'my_plugin_init' );
But neither add_action
hook seems to work. Ajax fails because it cannot find the ajax function in inc/my-plugin-functions.php
.
If I place the ajax function in the plugin loader, everything works as expected:
function my_plugin_etc() {
$title = sanitize_text_field( $_POST['title'] );
$meta = update_post_meta(1234, 'test_key', $title);
if ( $meta != false )
echo json_encode(array('status' => 'success', 'message' => 'Title added as postmeta.') );
else
echo json_encode(array('status' => 'error', 'message' => 'There was a problem.' ) );
wp_die();
}
add_action("wp_ajax_my_plugin_etc", "my_plugin_etc");
I'd rather not put the ajax function in the plugin loader.
What is the proper hook to use to include a file so that the ajax function in that file is registered?
my_plugint_init()
a typo?