Skip to content

Instantly share code, notes, and snippets.

@psdtohtml5
Created April 12, 2013 10:39
Show Gist options
  • Save psdtohtml5/5371167 to your computer and use it in GitHub Desktop.
Save psdtohtml5/5371167 to your computer and use it in GitHub Desktop.
WordPress : Add Meta Boxes
// Add Meta Boxes
$key = "portfolio"; // POST TYPE NAME
$meta_boxes = array(
"caption" => array(
"name" => "caption", // "name" attribute for input element
"title" => "Portfolio Item Caption", // "lable" of the field
"description" => "Description for this field" // helpful description shown in WordPress Admin Panel
),
"gallery" => array(
"name" => "gallery-id",
"title" => "Gallery ID",
"description" => "Description for this field"
)
);
/**************************************
* NO NEED TO EDIT ANYTHING BELOW THIS *
***************************************/
function wpb_create_meta_box() {
global $key;
if( function_exists( 'add_meta_box' ) ) {
add_meta_box( 'new-meta-boxes', ucfirst( $key ) . ' Options', 'display_meta_box', $key, 'normal', 'high' );
}
}
function display_meta_box() {
global $post, $meta_boxes, $key;
?>
<div class="form-wrap">
<?php
wp_nonce_field( plugin_basename( __FILE__ ), $key . '_wpnonce', false, true );
foreach($meta_boxes as $meta_box) {
$data = get_post_meta($post->ID, $key, true);
?>
<div class="form-field form-required">
<label for="<?php echo $meta_box[ 'name' ]; ?>"><?php echo $meta_box[ 'title' ]; ?></label>
<textarea name="<?php echo $meta_box[ 'name' ]; ?>"><?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?></textarea>
<p><?php echo $meta_box[ 'description' ]; ?></p>
</div>
<?php } ?>
</div>
<?php
}
function wpb_save_meta_box( $post_id ) {
global $post, $meta_boxes, $key;
foreach( $meta_boxes as $meta_box ) {
$data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ];
}
if ( !wp_verify_nonce( $_POST[ $key . '_wpnonce' ], plugin_basename(__FILE__) ) )
return $post_id;
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
update_post_meta( $post_id, $key, $data );
}
add_action( 'admin_menu', 'wpb_create_meta_box' );
add_action( 'save_post', 'wpb_save_meta_box' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment