Do I need a nonce field for every meta box I add to my custom post type admin?

I would recommend so.

You do (and should) have your own nonce with which to check the origin of the data and the intent of the user. If you have just one nonce for a metabox – then you run into problems if that metabox is removed (not the same as hidden). If removed the second metabox will (or at least should) never save since the nonce is longer sent.

Of course from a security point of view, nothing is added by a second nonce – unless you ever wish to only update one metabox and not the other: nonces should be unique to the action.


Edit

As pointed out there is only one form for the post edit screen. So, in theory, you only need one nonce field with which to validate the action and the origin of the data. However, since metaboxes can be removed – by having a nonce field in only one metabox there is no guarantee the nonce will be there. By placing a nonce field in each metabox you can check if data from that metabox has been sent (and is actually from where you think it is) prior to processing any data. E.g:

save_post_call_back($post_id){

  //Check this is not an auto-save route

  if(nonce of metabox1 present and valid){
     //Process data from metabox1
  }else{
    //Either metabox removed - or invalid nonce. Take no action.
  }

  if(nonce of metabox2 present and valid){
     //Process data from metabox2
  }else{
    //Either metabox removed - or invalid nonce. Take no action.
  }

}

The name of the nonce field should be unique to the metabox (and not clash with any other nonces that are present on the form from other plug-ins).

The nonce value should be unique to the action (and this generally should include the origin of the data (e.g. edit-post as opposed to quick-edit)). I generally include the post ID too.

Leave a Comment