Tao Custom Fields (meta-box) ko can plugin

Step 1. Define meta box with all needed fields

Open the functions.php file, and put the following code into it:
  1. $prefix = 'dbt_';
  2. $meta_box = array(
  3. 'id' => 'my-meta-box',
  4. 'title' => 'Custom meta box',
  5. 'page' => 'post',
  6. 'context' => 'normal',
  7. 'priority' => 'high',
  8. 'fields' => array(
  9. array(
  10. 'name' => 'Text box',
  11. 'desc' => 'Enter something here',
  12. 'id' => $prefix . 'text',
  13. 'type' => 'text',
  14. 'std' => 'Default value 1'
  15. ),
  16. array(
  17. 'name' => 'Textarea',
  18. 'desc' => 'Enter big text here',
  19. 'id' => $prefix . 'textarea',
  20. 'type' => 'textarea',
  21. 'std' => 'Default value 2'
  22. ),
  23. array(
  24. 'name' => 'Select box',
  25. 'id' => $prefix . 'select',
  26. 'type' => 'select',
  27. 'options' => array('Option 1', 'Option 2', 'Option 3')
  28. ),
  29. array(
  30. 'name' => 'Radio',
  31. 'id' => $prefix . 'radio',
  32. 'type' => 'radio',
  33. 'options' => array(
  34. array('name' => 'Name 1', 'value' => 'Value 1'),
  35. array('name' => 'Name 2', 'value' => 'Value 2')
  36. )
  37. ),
  38. array(
  39. 'name' => 'Checkbox',
  40. 'id' => $prefix . 'checkbox',
  41. 'type' => 'checkbox'
  42. )
  43. )
  44. );
Let me explain the code:
In the beginning of the code, we defined a prefix:
  1. $prefix = 'dbt_';
This prefix will be added before all of our custom fields. Using prefix can prevent us from conflicting with other scritps that also use custom fields.
The next variable $meta_box will hold all information about our meta box and all custom fields we need. Let’s look at the first lines:
  1. $meta_box = array(
  2. 'id' => 'my-meta-box-1',
  3. 'title' => 'Custom meta box',
  4. 'page' => 'post',
  5. 'context' => 'normal',
  6. 'priority' => 'high',
These are meta box’s attributes:
  • id: just the ID of meta box, each meta box has an unique ID
  • title: the meta box title
  • page: The type of Write screen on which to show the meta box (‘post’, ‘page’, or ‘link’) (for WP 3.0, see note below)
  • context: The part of the page where the meta box should be shown (‘normal’, ‘advanced’ or (since 2.7) ‘side’)
  • priority: The priority within the context where the boxes should show (‘high’ or ‘low’)
For WordPress 3.0: If you’re using custom post type in WordPress 3.0 (for example you created new post type 'album'), you can change the 'page' attribute to 'album' to show the meta box in the editing screen of 'album' only.
Below are custom fields. Each custom field has the following attributes:
  • name: The name of the custom field, it will be shown to user.
  • desc: A short description explaining what it is to the user.
  • id: the id of the field, prefixed by the $prefix. It will be used to store the custom field value
  • type: the input type: select, text, textarea, radio or checkbox
  • options: used to declare an array of options for a some type of input (select, radio)
  • std: the default value of the custom field.

Step 2. Add meta box to Edit Page

To add a meta box to edit page, we hook to admin_menu action as in the following code:
  1. add_action('admin_menu', 'mytheme_add_box');
  2. // Add meta box
  3. function mytheme_add_box() {
  4. global $meta_box;
  5. add_meta_box($meta_box['id'], $meta_box['title'], 'mytheme_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']);
  6. }
The function is used to add a meta box to edit page is add_meta_box. This function has 6 parameters:
  1. add_meta_box($id, $title, $callback, $page, $context, $priority);
Each parameter has the same meaning as the meta box’s attribute (I’ve explained it before), except the $callback parameter. The $callback parameter is the name of callback function, used to display HTML code of custom fields. In our situation, this function is mytheme_show_box.

Step 3. Show meta box

We need to implement the callback function mytheme_show_box to show HTML code of all custom fields. The function looks like:
  1. // Callback function to show fields in meta box
  2. function mytheme_show_box() {
  3. global $meta_box, $post;
  4. // Use nonce for verification
  5. echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
  6. echo '<table class="form-table">';
  7. foreach ($meta_box['fields'] as $field) {
  8. // get current post meta data
  9. $meta = get_post_meta($post->ID, $field['id'], true);
  10. echo '<tr>',
  11. '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
  12. '<td>';
  13. switch ($field['type']) {
  14. case 'text':
  15. echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '<br />', $field['desc'];
  16. break;
  17. case 'textarea':
  18. echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>', '<br />', $field['desc'];
  19. break;
  20. case 'select':
  21. echo '<select name="', $field['id'], '" id="', $field['id'], '">';
  22. foreach ($field['options'] as $option) {
  23. echo '<option ', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
  24. }
  25. echo '</select>';
  26. break;
  27. case 'radio':
  28. foreach ($field['options'] as $option) {
  29. echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name'];
  30. }
  31. break;
  32. case 'checkbox':
  33. echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
  34. break;
  35. }
  36. echo '</td><td>',
  37. '</td></tr>';
  38. }
  39. echo '</table>';
  40. }
It is a large function, isn’t it? But it’s not very hard to understand.
In the very first of the function, we create a hidden field to store a nonce number. It’s required toverify this came from the our screen and with proper authorization:
  1. echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
And then we display all custom fields in a table. Using the PHP foreach loop, each field is displayed based on its type. Before displaying the custom field’s value for select, radio and checkbox input types, we need to check the “saved” value (if it already exists) and compare to the default values. This is done via the line code:
  1. // get current post meta data
  2. $meta = get_post_meta($post->ID, $field['id'], true);
The HTML code of each custom fields is just input fields with some attributes like id, name, value, etc.
After this is done, we’ll get the meta box on Editing Page like this (click to enlarge):
custom meta box How To Create A Better Meta Box In WordPress Post Editing Page

Step 4. Save meta data when post is edited

To save the data of custom fields, we need to hook to save_post action:
  1. add_action('save_post', 'mytheme_save_data');
  2. // Save data from meta box
  3. function mytheme_save_data($post_id) {
  4. global $meta_box;
  5. // verify nonce
  6. if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) {
  7. return $post_id;
  8. }
  9. // check autosave
  10. if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
  11. return $post_id;
  12. }
  13. // check permissions
  14. if ('page' == $_POST['post_type']) {
  15. if (!current_user_can('edit_page', $post_id)) {
  16. return $post_id;
  17. }
  18. } elseif (!current_user_can('edit_post', $post_id)) {
  19. return $post_id;
  20. }
  21. foreach ($meta_box['fields'] as $field) {
  22. $old = get_post_meta($post_id, $field['id'], true);
  23. $new = $_POST[$field['id']];
  24. if ($new && $new != $old) {
  25. update_post_meta($post_id, $field['id'], $new);
  26. } elseif ('' == $new && $old) {
  27. delete_post_meta($post_id, $field['id'], $old);
  28. }
  29. }
  30. }
In the beginning of the function, we check the nonce to make sure that the data is come from edit post with proper authorization.
And then, we check the autosave feature. We don’t want to save the data automatically via autosave feature. We want to save the data only when use clicked on the button Save (or Publish). If you really want to save the data via autosave feature, you can delete these lines (don’t worry, they don’t affect to the rest of code).
  1. // check autosave
  2. if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
  3. return $post_id;
  4. }
The last check is the user capability. We just check if user can edit post or page.
After all of verifications, we use the foreach loop to walk through every custom fields. If the custom fields is not in the database or it is changed, we update it (note: the update_post_meta also adds post meta when the meta is not present in database). If the custom fields is empty, we delete it from database.
When the post is edited or published, we can check the keys and values of custom fields as in the following screenshot (click to enlarge):
custom fields How To Create A Better Meta Box In WordPress Post Editing Page
As you can see, that works!

Enjoy meta box script for WordPress

Nhận xét

Bài đăng phổ biến từ blog này

Code chống iframe

Code đặt mật khẩu cho file PHP

Hướng dẫn cài đặt và cấu hình PHP Zend OPcache trên CentOS