Created
August 20, 2019 14:22
-
-
Save wordpress-lab/f49b70e5fa169d35e9e4fb19b6229764 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Register a meta box using a class. | |
*/ | |
class WPDocs_Custom_Meta_Box { | |
/** | |
* Constructor. | |
*/ | |
public function __construct() { | |
if ( is_admin() ) { | |
add_action( 'load-post.php', array( $this, 'init_metabox' ) ); | |
add_action( 'load-post-new.php', array( $this, 'init_metabox' ) ); | |
} | |
} | |
/** | |
* Meta box initialization. | |
*/ | |
public function init_metabox() { | |
add_action( 'add_meta_boxes', array( $this, 'add_metabox' ) ); | |
add_action( 'save_post', array( $this, 'save_metabox' ), 10, 2 ); | |
} | |
/** | |
* Adds the meta box. | |
*/ | |
public function add_metabox() { | |
add_meta_box( | |
'my-meta-box', | |
__( 'My Meta Box', 'textdomain' ), | |
array( $this, 'render_metabox' ), | |
'post', | |
'advanced', | |
'default' | |
); | |
} | |
/** | |
* Renders the meta box. | |
*/ | |
public function render_metabox( $post ) { | |
// Add nonce for security and authentication. | |
wp_nonce_field( 'custom_nonce_action', 'custom_nonce' ); | |
} | |
/** | |
* Handles saving the meta box. | |
* | |
* @param int $post_id Post ID. | |
* @param WP_Post $post Post object. | |
* @return null | |
*/ | |
public function save_metabox( $post_id, $post ) { | |
// Add nonce for security and authentication. | |
$nonce_name = isset( $_POST['custom_nonce'] ) ? $_POST['custom_nonce'] : ''; | |
$nonce_action = 'custom_nonce_action'; | |
// Check if nonce is valid. | |
if ( ! wp_verify_nonce( $nonce_name, $nonce_action ) ) { | |
return; | |
} | |
// Check if user has permissions to save data. | |
if ( ! current_user_can( 'edit_post', $post_id ) ) { | |
return; | |
} | |
// Check if not an autosave. | |
if ( wp_is_post_autosave( $post_id ) ) { | |
return; | |
} | |
// Check if not a revision. | |
if ( wp_is_post_revision( $post_id ) ) { | |
return; | |
} | |
} | |
} | |
new WPDocs_Custom_Meta_Box(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment