A complete, safe pattern for an admin-ajax.php request: a nonce, a capability check, cleaned input and a JSON response.
// 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 );
*/
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.
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.
permission_callback is the modern alternative.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}}.