Add Metabox in wordpress

There are several plugins available in wordpress which helps to add metabox .  It’s a ridiculous  task for worpress programmer to use them as already we have a simple action.

function adding_custom_boxes( $post_type, $post ) {
    add_meta_box( 
        'my-meta-box',
        __( 'My Meta Box' ),
        'render_my_meta_box',
        'post',     // here you can mention your post_type 
               for multiple post type pass array of them  
        'normal',
        'default'
    );
}

// action to add meta box
add_action('add_meta_boxes','adding_custom_boxes',10,2);

//function to add metabox html
function render_my_meta_box(){

}

Once you have metabox in backend, you will need to save metabox data for further retrieval.
You can save metabox data on post save and post update action.

function my_project_save_metabox_data( $post_id ) {
   /*
    *  here you can write your code to save metabox data
    *  you may get it with $_POST['field_name']
    *  you can save it in anywhere or postmeta.  
    */
}
add_action( 'save_post', 'my_project_save_metabox_data' );

Published by

One thought on “Add Metabox in wordpress”

Leave a Reply

Your email address will not be published. Required fields are marked *