Skip to content

Instantly share code, notes, and snippets.

@abelcallejo
Last active October 20, 2023 21:29
Show Gist options
  • Save abelcallejo/160a3a08fb3c3cb4c0f80055aead17d4 to your computer and use it in GitHub Desktop.
Save abelcallejo/160a3a08fb3c3cb4c0f80055aead17d4 to your computer and use it in GitHub Desktop.
Creating and managing nonce on Wordpress

Creating and managing nonce on Wordpress

Creating a raw nonce value

Action-based

$nonce = wp_create_nonce( 'my-action_'.$post->ID ); // 295a686963

HTML sample

<input type="hidden" id="_wpnonce" name="_wpnonce" value="<?php echo $nonce; ?>" />

Creating a nonce value via PHP helper

PHP

wp_nonce_field( 'my-action_'.$post->ID );

/**
 * Echos 2 fields:
<input type="hidden" id="_wpnonce" name="_wpnonce" value="295a686963" />
<input type="hidden" name="_wp_http_referer" value="/wp-admin/post.php" />
 * the nonce itself and the referrer
 */

Verifying a nonce value

Action-based

$is_valid_nonce = wp_verify_nonce( '295a686963', 'my-action_1' ); // true or false

Verifying a nonce value via PHP Helper

PHP

$is_valid_nonce = wp_verify_nonce( '295a686963', 'my-action_1' ); // true or false
$is_valid_referrer = check_admin_referer( 'my-action_1' ); // true or false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment