Pages

Showing posts with label metaboxes. Show all posts
Showing posts with label metaboxes. Show all posts

Thursday, November 8, 2012

Add Metaboxes and Metafields to your wordpress posts

Add Metaboxes and metafields to your wordpress posts


 add_action('add_meta_boxes','mypost_add_custom_box');  
 add_action('save_post','myplugin_save_postdata');  
 function mypost_add_custom_box() {  
   add_meta_box(  
     'myplugin_sectionid',  
     __('Post Type Selection','myplugin_textdomain'),  
     'myplugin_inner_custom_box',  
     'post'  
   );  
 }  
 function myplugin_inner_custom_box( $post ) {  
  wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );  
  // The actual fields for data entry  
  $scheckval=esc_attr(get_post_meta($post->ID,'slider_post',true));  
  $pcheckval=esc_attr(get_post_meta($post->ID,'popular_post',true));  
  if($scheckval=='on')  
  echo '<input type="checkbox" id="myplugin_slider_field" name="myplugin_slider_field" checked="checked"/>';  
  else  
  echo '<input type="checkbox" id="myplugin_slider_field" name="myplugin_slider_field"/>';  
  echo '<label for="myplugin_slider_field">';  
     _e("Slider Post", 'myplugin_sdomain' );  
  echo '</label> ';  
  if($pcheckval=='on')  
  echo '<input type="checkbox" id="myplugin_popular_field" name="myplugin_popular_field" checked="checked"/>';  
  else  
  echo '<input type="checkbox" id="myplugin_popular_field" name="myplugin_popular_field"/>';  
  echo '<label for="myplugin_popular_field">';  
     _e("Popular Post", 'myplugin_pdomain' );  
  echo '</label>';  
 }  
 /* When the post is saved, saves our custom data */  
 function myplugin_save_postdata( $post_id ) {  
  // verify if this is an auto save routine.  
  // If it is our form has not been submitted, so we dont want to do anything  
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )  
    return;  
  // verify this came from the our screen and with proper authorization,  
  // because save_post can be triggered at other times  
  if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )  
    return;  
  // Check permissions  
  if ( 'page' == $_POST['post_type'] )  
  {  
   if ( !current_user_can( 'edit_page', $post_id ) )  
     return;  
  }  
  else  
  {  
   if ( !current_user_can( 'edit_post', $post_id ) )  
     return;  
  }  
  // OK, we're authenticated: we need to find and save the data  
  if($_POST['myplugin_slider_field']=='on')  
  $smydata=$_POST['myplugin_slider_field'];  
  else  
  $smydata='off';  
  if($_POST['myplugin_popular_field']=='on')  
  $pmydata=$_POST['myplugin_popular_field'];  
  else  
  $pmydata='off';  
  update_post_meta($post_id,'slider_post',$smydata);  
  update_post_meta($post_id,'popular_post',$pmydata);  
 }