Skip to content

Nonces

Nonces are a way to prevent cross-site request forgery (CSRF) attacks. They are used to ensure that a request is coming from the expected source, and not from an attacker.

Metapress provides a simple way to generate and verify nonces for your plugin. To generate a nonce, you can use the Nonce class provided by the framework.

For more information about nonces, see the WordPress documentation.

Generating a nonce

To generate a nonce, you can use the Nonce class provided by the framework and create a new instance of it. The constructor takes a required slug as an argument, which is used to identify the nonce.

php
use Sematico\Metapress\Nonces;

$nonce = new Nonce('my-slug');

Now that you have a nonce instance, you have access to several methods to generate and verify nonces.

Making the nonce

To generate a nonce, you can use the make() method of the nonce instance. Behind the scenes, this method uses the wp_create_nonce() function to generate a unique nonce.

php
$nonce = new Nonce('my-slug');

$token = $nonce->make();

Rendering the nonce field

To render the nonce field in your plugin, you can use the render() method of the nonce instance. Behind the scenes, this method uses the wp_nonce_field() function to render the field.

php
$nonce = new Nonce('my-slug');

echo $nonce->render();

Generating a nonced URL

To generate a nonced URL, you can use the url() method of the nonce instance.

php
$nonce = new Nonce('my-slug');

$url = $nonce->url();

This will generate a URL that includes the nonce as a query parameter.

Verifying a nonce

To verify a nonce, you can use the check() method of the nonce instance. This method takes the nonce token as an argument and returns true if the nonce is valid, and false otherwise.

Abort on nonce failure

If you want to abort the execution of your plugin if the nonce is not valid, you can use the check_or_fail() method of the nonce instance.

php
$nonce = new Nonce('my-slug');

$nonce->check_or_fail();

This will check the nonce and throw an exception if it is not valid.

Reference documentation