let’s send ajax request in wordpress using wpnonce
Hei, I am not going to discuss what is wpnonce and why you should use this in your plugin or how important to use this to secure your plugin đ
But here I am going to discuss how you can use wpnonce in ajax request, I mean if your plugin handles ajax request.
Steps that we need to follow are:
One: Create wpnonce value.
Two: Send wpnonce value as an extra parameter with ajax requestion
Three: Check ajax referrer with the wpnonce value that was created in step one and sent in step two.
Ok, how to create a wpnonce value ?
we need to use wordpress function wp_create_nonce() . See wordpress codex here.
< ?php $my_wpnonce= wp_create_nonce (‘you-look-nice’); ?> // “you-look-nice” is just a string, u can use whatever u want. here $my_wpnonce will get a hash from wp_create_nonce. Oh that is not direct hash of “you-look-nice” but based on user id, time and that string. To know more about this function please check pluggable.php in wp-includes folder
Now send wpnonce value $my_wpnonce as an extra parameter while seding ajax req.
Now to process the ajax request in your script at first u need to include the wp-config.php or how u handle this.. no problem. Just use this line after this to check the ajax referrer.
< ?php check_ajax_referer(“you-look-nice”); ?> /// “you-look-nice” ya same string that u used making wpnoce….
If the nonce value is not same then the hacker will be just got fucked!
note: check codex here for the function check_ajax_referer.
That’s it man.
Great info. The plugin works very nice. Thanks.