Skip to content

Instantly share code, notes, and snippets.

@harisrozak
Last active June 14, 2022 07:52
Show Gist options
  • Save harisrozak/fad09760b7323ea33ce7909150654d1a to your computer and use it in GitHub Desktop.
Save harisrozak/fad09760b7323ea33ce7909150654d1a to your computer and use it in GitHub Desktop.
Add hidden nonce field admin post / post type editor
<?php
/**
* Add hidden nonce field to project post type editor.
*
* @param WP_Post $post Post object data.
*/
function harisrozak_add_hidden_nonce_field( $post ) {
// Only render on a certain post type.
if ( 'project' !== $post->post_type ) {
return;
}
// Prevent the nonce field to be rendered multiple times.
if ( defined( 'HARISROZAK_MAIN_NONCE_FIELD_RENDERED' ) ) {
return;
}
define( 'HARISROZAK_MAIN_NONCE_FIELD_RENDERED', 1 );
wp_nonce_field( 'harisrozak_admin_project_form', 'harisrozak_admin_project_form_nonce' );
}
add_action( 'edit_form_top', 'harisrozak_add_hidden_nonce_field' );
/**
* Handles saving the meta box.
*
* @param int $post_id Post ID.
* @param WP_Post $post Post object.
* @return null
*/
public function harisrozak_save_metabox( $post_id, $post ) {
$post_data = isset( $_POST ) ? wp_unslash( $_POST ) : array();
$nonce = isset( $post_data['harisrozak_admin_project_form_nonce'] ) ? $post_data['harisrozak_admin_project_form_nonce'] : null;
if ( ! wp_verify_nonce( $nonce, 'harisrozak_admin_project_form' ) ) {
return;
}
// The save_post data handler lies here.
}
add_action( 'save_post', 'harisrozak_save_metabox', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment