REST API & Developer PHP Intermediate

Handle an AJAX Request Securely

A complete, safe pattern for an admin-ajax.php request: a nonce, a capability check, cleaned input and a JSON response.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 36 lines
// 1. The handler. "wp_ajax_" runs for logged-in users only.
add_action( 'wp_ajax_nahnu_toggle_featured', function (): void {
	check_ajax_referer( 'nahnu_toggle_featured', 'nonce' );

	$post_id = absint( $_POST['post_id'] ?? 0 );
	if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
		wp_send_json_error( [ 'message' => 'Not allowed.' ], 403 );
	}

	$featured = ! get_post_meta( $post_id, 'nahnu_featured', true );
	update_post_meta( $post_id, 'nahnu_featured', $featured ? 1 : 0 );

	wp_send_json_success( [ 'featured' => $featured ] );
} );

// 2. Give the browser the URL and a nonce.
add_action( 'admin_enqueue_scripts', function ( string $hook ): void {
	if ( 'edit.php' !== $hook ) {
		return;
	}
	wp_add_inline_script(
		'jquery-core',
		'window.nahnuAjax = ' . wp_json_encode( [
			'url'   => admin_url( 'admin-ajax.php' ),
			'nonce' => wp_create_nonce( 'nahnu_toggle_featured' ),
		] ) . ';'
	);
} );

/* 3. Call it from JavaScript:
fetch( nahnuAjax.url, {
	method: 'POST',
	credentials: 'same-origin',
	body: new URLSearchParams( { action: 'nahnu_toggle_featured', nonce: nahnuAjax.nonce, post_id: 123 } ),
} ).then( ( r ) => r.json() ).then( console.log );
*/

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

admin-ajax.php is still the simplest way to run PHP from a button click in wp-admin. Most security problems in plugins come from AJAX handlers that skip one of the checks, so this snippet shows the full pattern.

How it works

The action sent with the request picks the hook: wp_ajax_nahnu_toggle_featured. Only logged-in users reach wp_ajax_ hooks. For visitors you’d also add wp_ajax_nopriv_, but think carefully before you do.

check_ajax_referer() checks the nonce and stops the request if it’s missing or wrong, which blocks requests forged by other sites. current_user_can() checks the user is allowed to change that specific post. absint() makes sure the ID is a whole number.
wp_send_json_success() and wp_send_json_error() send a JSON response with the right headers and stop the script.

Things to watch

  • A nonce proves the request came from your page. It does not prove the user may do the action. Always check capabilities too.
  • For new projects, a REST API route with a permission_callback is the modern alternative.

How to test it

Open Posts → All Posts, then run the JavaScript from step 3 in the browser console with a real post ID. You should get {"success":true,"data":{"featured":true}}.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only