Last active
June 14, 2022 07:52
-
-
Save harisrozak/fad09760b7323ea33ce7909150654d1a to your computer and use it in GitHub Desktop.
Add hidden nonce field admin post / post type editor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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