Nonces helps protect your actions from misuses by generating and verifying tokens.

Nonces are used to verify if the person, who's doing a specific operation, are entitled to do so. It identifies operation between requests.

Basics of Nonces

Injecting the Assely\Nonce\NonceFactory provides access to the nonce service. However, you can also use Nonce facade.

use Assely\Nonce\NonceFactory;

public function __construct(NonceFactory $nonce) {
    $this->token = $nonce->create('key');

Creating Nonces

Calling create method will return generated token.

$token = Nonce::create($slug);

You have to pass this token further and verify before finalizing the operation. Usually, this token is transferred as part of the request, as URL query parameter or form hidden input.

Verifying Nonces

You can validate given token with verify method.

if (Nonce::verify($token)) {
    // token is valid

Outputing Nonce Inputs

If you need to add nonce inputs to your form there is fields method that will help you. It outputs HTML inputs markup with already generated tokens.


Might echo something like:

<input type="hidden" id="_token-key-nonce" name="_token-key-nonce" value="b192fc4204" />
<input type="hidden" name="_wp_http_referer" value="resource/url/path" />