Strange use of WordPress add_action()

steva
steva used Ask the Experts™
on
I expect add_action() to specify a hook name and then a function to call when the hook fires, but I came across the text below in "WordPress Web Application Development, 2nd ed on page 29:

 “We need to define AJAX handler functions using the WordPress add_action function:
add_action( ‘wp_ajax_mark_answer_status’, ‘wpwa_mark_answer_status’ );

There's no existing hook with the name "wp_ajax_mark_answer_status" so could someone explain what's going on?

Thanks for your help.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
PHP Web Developer
Commented:
The hook is actually "wp_ajax_<action passed as a request>" - see the Codex for a full explanation.

TLDR version: when you make an AJAX call, you need to add an "action" parameter, e.g. "mark_answer_status" as in
http://www.example.com/wp-admin/admin-ajax.php?action=mark_answer_status

Open in new window

and admin-ajax.php fires the hook "wp_ajax_mark_answer_status" as a result (admin-ajax.php line 80 onwards):
if ( is_user_logged_in() ) {
	/**
	 * Fires authenticated AJAX actions for logged-in users.
	 *
	 * The dynamic portion of the hook name, `$_REQUEST['action']`,
	 * refers to the name of the AJAX action callback being fired.
	 *
	 * @since 2.1.0
	 */
	do_action( 'wp_ajax_' . $_REQUEST['action'] );
} else {
	/**
	 * Fires non-authenticated AJAX actions for logged-out users.
	 *
	 * The dynamic portion of the hook name, `$_REQUEST['action']`,
	 * refers to the name of the AJAX action callback being fired.
	 *
	 * @since 2.8.0
	 */
	do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
}

Open in new window

Author

Commented:
Thank you!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial