Last active
July 29, 2022 07:06
-
-
Save mikeott/f4d7208d238af738f2af2c1b7bc52954 to your computer and use it in GitHub Desktop.
WordPress nonce anchor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Only allow access to a URL if nonce passed. | |
Nonce docs: https://codex.wordpress.org/WordPress_Nonces | |
*/ | |
/* The URL you want to protect */ | |
$the_url = plugins_url() . '/my-plugin/top-secret.php'; | |
?> | |
<?php | |
/* | |
This will output HTML something like this example (with a different _wpnonce value of course): | |
<a href="https://example.com/wp-content/plugins/my-plugin/top-secret.php?_wpnonce=b197fd4203">Do it</a> | |
*/ | |
?> | |
<a href="<?php echo wp_nonce_url( $the_url, 'my_custom_action' ); ?>">Do it</a> | |
<?php | |
/* | |
Place the following code inside the file you want to protect. | |
In this example, the file is top-secret.php | |
*/ | |
if( wp_verify_nonce( $_GET['_wpnonce'], 'my_custom_action' ) ) { | |
/* Congrats, nonce passed now do something cool. */ | |
} else { | |
/* Nonce failed, exit. | |
This will happen if the nonce expired, or if someone tried to access top-secret.php directly. */ | |
exit; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment