Created
June 30, 2017 02:56
-
-
Save mguay22/3ca5e37d2f09540ae7f3643bcb1fba81 to your computer and use it in GitHub Desktop.
Custom WordPress Metabox
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
add_action( 'add_meta_boxes', 'mg_mb_create' ); | |
function mg_mb_create() { | |
add_meta_box( 'mg-meta', 'My Custom Meta Box', 'mg_mb_function', 'post', 'normal', 'high' ); | |
} | |
function mg_mb_function( $post ) { | |
// Retrieve the metadata values if they exist. | |
$mg_mb_name = get_post_meta( $post->ID, '_mg_mb_name', true ); | |
$mg_mb_genre = get_post_meta( $post->ID, '_mg_mb_genre', true ); | |
echo 'Please fill out the information below'; | |
?> | |
<p> | |
Name: | |
<input type="text" name="mg_mb_name" value="<?php echo esc_attr( $mg_mb_name ); ?>" /> | |
</p> | |
<p> | |
Genre: | |
<select name="mg_mb_genre"> | |
<option <value="rock" <?php selected( $mg_mb_genre, 'rock' ); ?>> | |
Rock | |
</option> | |
<option <value="jazz" <?php selected( $mg_mb_genre, 'jazz' ); ?>> | |
Jazz | |
</option> | |
<option <value="hip-hop" <?php selected( $mg_mb_genre, 'hip-hop' ); ?>> | |
Hip-Hop | |
</option> | |
</select> | |
</p> | |
<?php | |
} | |
// Hook to save the metabox data | |
add_action( 'save_post', 'mg_mb_save_meta' ); | |
function mg_mb_save_meta( $post_id ) { | |
// Verify the metadata is set. | |
if ( isset( $_POST['mg_mb_name'] ) ) { | |
// Save the metadata. | |
update_post_meta( $post_id, '_mg_mb_name', strip_tags( $_POST['mg_mb_name'] ) ); | |
update_post_meta( $post_id, '_mg_mb_genre', strip_tags( $_POST['mg_mb_genre'] ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment