Confusion on WP Nonce usage in my Plugin

Nonces are one time use limited life unique numbers. You can clone them but the problem you’ll see is that once sent back to the server and validated, the other clones will become invalid.

You have a few ways to handle this.

  1. Generate all your boxes on the server and discard the Javascript.
  2. Use Ajax to request a new nonce for each cloned box.
  3. My preferred choice, Use Ajax to request the server to create the clone.

Either way, your nonce needs to come from the server. The way WP handles this (for it’s Categories metabox for example) is to generate the Nonce name from the taxonomy name. You could use possibly the post value or image name for this.

<?php wp_nonce_field('add-' . $name, 'add-' . $name . '_nonce', false); ?>

Doing this would also require you to store the $name within a hidden field on your page.

<input id="<?php echo $name; ?>" type="hidden" value="add-<?php echo $name; ?>" />

From within your Ajax send both the unique name and the nonce back to the server validate and return whatever you want.

As for your other question “Is the nonce necessary?”. Well, it depends. I would suggest, any time you make changes to your database from form data, then yes they are required. If you’re only retrieving data, then no they’re not. But they will still come in useful for invalidating requests that may have been bookmarked or cached somewhere. I can’t remember exactly, I think their lifetime is about 12 hours.