Created
April 10, 2015 16:36
-
-
Save trys/24cf76cc8d00b331d9b9 to your computer and use it in GitHub Desktop.
Add metabox to WordPress
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
/** | |
* Add Meta Box | |
* | |
* @return void | |
*/ | |
function projectnamespace_add_meta_box() { | |
add_meta_box( | |
'projectnamespace_meta_box_id', | |
'Meta box title', | |
'projectnamespace_meta_box_callback', | |
'page' | |
); | |
} | |
add_action( 'add_meta_boxes', 'projectnamespace_add_meta_box' ); | |
/** | |
* Add meta box fields | |
* | |
* @param object $post | |
* @return void | |
*/ | |
function projectnamespace_meta_box_callback( $post ) { | |
wp_nonce_field( 'projectnamespace_meta_nonce', 'projectnamespace_meta_nonce_field' ); | |
echo '<input type="text" placeholder="Placeholder" class="widefat" id="_projectnamespace_field" name="_projectnamespace_field" value="' . esc_attr( $post->_projectnamespace_field ) . '" />'; | |
} | |
/** | |
* Save meta box | |
* | |
* @param int $post_id | |
* @return mixed | |
*/ | |
function projectnamespace_save_meta_box( $post_id ) { | |
if ( ! isset( $_POST[ 'projectnamespace_meta_nonce_field' ] ) ) | |
return; | |
if ( ! wp_verify_nonce( $_POST[ 'projectnamespace_meta_nonce_field' ], 'projectnamespace_meta_nonce' ) ) | |
return; | |
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) | |
return; | |
if ( isset( $_POST[ 'post_type' ] ) && 'page' == $_POST[ 'post_type' ] ) | |
if ( ! current_user_can( 'edit_page', $post_id ) ) | |
return; | |
else | |
if ( ! current_user_can( 'edit_post', $post_id ) ) | |
return; | |
$fields = array( '_projectnamespace_field' ); | |
foreach ( $fields as $field ) | |
if ( ! isset( $_POST[ $field ] ) ) | |
continue; | |
else | |
update_post_meta( $post_id, $field, sanitize_text_field( $_POST[ $field ] ) ); | |
} | |
add_action( 'save_post', 'projectnamespace_save_meta_box' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment