Here is some working code for a promo modal but is this a safe and appropriate way to use the wordpress nonce in an ajax request?
Create the nonce in the tmp: $ajax_nonce = wp_create_nonce( "mynonce" ); Example URL: www.mysite.com/#345345
var asdf = location.hash.match(/^#?(.*)$/)[1];
if (asdf) {
$productID = asdf;
if ($.cookie("modalshow") === undefined) {
var expiryDate = new Date();
var minutes = 0.20; //12 seconds
expiryDate.setTime(expiryDate.getTime() + (minutes * 60 * 1000));
$.cookie("modalshow", "exists", { path: '/', expires: expiryDate });
var data = {
action: 'my_action',
product_id: $productID,
security: '<?php echo $ajax_nonce; ?>'
};
var ajaxurl = '/wp-admin/admin-ajax.php';
$.post(ajaxurl, data, function(response) {
$(".modal-content").append(response);
$('#Modal').modal({ show:true });
});
} //no cookie
};//if match
Plugin:
add_action( 'wp_ajax_my_action', 'my_action_function' );
function my_action_function() {
check_ajax_referer( 'mynonce', 'security' );
if( isset($_POST['product_id']) ) {
$my_report_num = $_POST['product_id']; // splash 443
$myposttype = get_post_type( $my_product_num );
if ( get_post_status( $my_product_num ) == 'publish' && $myposttype == "df_product" ) {
//we're good
$theid = $my_product_num;
} else {
$theid = "876";
}
//fedtch content using $theid
die();
} // end if
die;
}
In the above php, get_post_type() uses get_post() which uses sanitize_post() - so there is some validation being done, and currently my plan is that if anything malicious is appended to the URL or sent by some other means in the client, that $theid will be set to my white listed number "876" - so do I need to do additional validation either in the client or in php?
Any assistance is appreciated, thanks!