Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example function used to demonstrate how meta data is typically saved in a WordPress theme or plugin. The gist is made public so that developers can contribute to the standard security boilerplate functionality in order to simplify, reduce, and improve our serialization functions.
<?php
/**
* An example function used to demonstrate how to use the `user_can_save` function
* that provides boilerplate security checks when saving custom post meta data.
*
* The ultimate goal is provide a simple helper function to be used in themes and
* plugins without the need to use a set of complex conditionals and constants.
*
* Instead, the aim is to have a simplified function that's easy to read and that uses
* WordPress APIs.
*
* The DocBlocks should provide all information needed to understand how the function works.
*/
public function save_meta_data( $post_id ) {
if( user_can_save( $post_id, 'meta_data_nonce' ) ) {
/* ---------------------------------------- */
/* -- Actual serialization work occurs here */
/* ---------------------------------------- */
} // end if
} // end save_meta_data
/**
* Determines whether or not the current user has the ability to save meta data associated with this post.
*
* @param int $post_id The ID of the post being save
* @param bool Whether or not the user has the ability to save this post.
*/
function user_can_save( $post_id, $nonce ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ $nonce ] ) && wp_verify_nonce( $_POST[ $nonce ], plugin_basename( __FILE__ ) ) );
// Return true if the user is able to save; otherwise, false.
return ! ( $is_autosave || $is_revision ) && $is_valid_nonce;
} // end user_can_save
@dukizuki
Copy link

dukizuki commented May 29, 2014

Hi Tom. maybe it's not correct place where I should ask this, but may I use this code snippet in commercial(Themeforest Theme) use? Thanks in advance..
^ Duke

@tamas-web
Copy link

tamas-web commented Oct 21, 2015

Just out of curiosity...
Why wouldn't I want to save an auto save as well?
Maybe I have some meta data, that may be needed with auto save as well.
Lastly I'm fairly new to Wordpress, experienced coder, but still new to it's API, so which is the code part that checks if the user can save or not?

From what i can make out:
$is_autosave = wp_is_post_autosave( $post_id );
check if the current save state is an auto save or not, not related to user_can stuff, I think
$is_revision = wp_is_post_revision( $post_id );
check if the current save state is a revision
$is_valid_nonce =...
well no arguing there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment