26
Oct
Creating Meta Box in Page/Post
- Category:
- Wordpress

Posted On : October 26, 2013
| No Comment
If want to add metabox in admin interface in posts/pages, then below simple code is useful.
Add below code in theme’s function.php file :
View Code PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | add_action('admin_init', 'add_my_metabox'); function add_my_metabox() { add_meta_box('port_cat_id', 'Portfolio Categories', 'my_metabox_callback', 'page', 'side'); // adding metabox in Pages add_meta_box('port_cat_id', 'Portfolio Categories', 'my_metabox_callback', 'post', 'side'); // adding metabox in Posts } //function to add dropdown of Portfolio Categories function my_metabox_callback() { $getcat = get_categories(); $postmeta = get_post_meta($_GET['post'], 'key1', true);?> <select name="category_name"> <option value="select category">Select Portfolio Category</option> foreach($getcat as $portcat) { <option <?php echo ($postmeta == $portcat->term_id) ? "selected=selected" : ""?> value="<?php echo $portcat->term_id;?>"><?php echo $portcat->cat_name;?></option> } </select> } |
Once above code is saved, will get dropdown metabox with posts categories on pages.
Now, to save metabox content, add below code in theme’s function.php file :
View Code PHP
1 2 3 4 5 6 | //save added metabox content add_action('save_post', 'update_page_portfolio_category'); function update_page_portfolio_category($post_id) { $mydata = $_POST['category_name']; update_post_meta($post_id, 'key1', $mydata); } |
- Tags: