Meta Box Script Update V3.0

Update: The script was turned into Meta Box WordPress plugin and is being developed. Visit plugin page to see more info and download latest version.

After 2 posts in series of creating meta box, I received many ideas and opinions that really helpful. I appreciate that, and I want to give big thanks to all our contributors.

It has been a while since the last version of meta box script (2.4.1). Today I want to show you the next major version (3.0) with many improvements in the code, which supports better for OOP, gives big opportunity to developers to extend the class. And of course, some field types are added as well as some bugs are fixed.

Let's go a bit in details.

Better support for Object-Oriented Programming

One of the major changes in this version is the class supports better for OOP. All functions for checking, showing and saving fields are separated in methods. For example, to check the upload field, there is a group of methods:

function __construct($meta_box) {
 $this->check_field_upload();
}
// Check field upload and add needed actions
function check_field_upload() {
 if ($this->has_field('image') || $this->has_field('file')) {
  add_action('post_edit_form_tag', array(&$this, 'add_enctype'));    // add data encoding type for file uploading
 }
}
function show_field_file($field, $meta) {
}
function save_field_file($post_id, $field, $old, $new) {
}

There're some advantages of this style of coding:

Allow developers easily to extend the class

Imagine that you want to extend the class that support another field type, for example link. All you need is defining corresponding methods that check, show and save this type of field. That's very similar to the code above.

In the download package, I also created an example to make this idea clearly. The class RW_Meta_Box_Taxonomy extends the class RW_Meta_Box, adds taxonomy type of field. You should read it carefully to know how to replicate for other types. Thank Manny Fresh for the code for taxonomy type.

1. The name of showing and saving methods should be show_field_{$type} and save_field_{$type} correspondingly.
2. Note that the original class has a common save method save_field that can handle most cases of saving field. If you don't write any method for saving field value (i.e. save_field_{$type} method), then save_field will be used.

Allow developers to re-define the look and feel of fields

If you don't like the appearance of fields, feel free re-define it. Just overwrite the written showing method.

For example, each field is showed in 2 cells of a row in the table. If you don't want 2 cells, but only 1 cell, you can re-define it like this:

class RW_Meta_Box_New extends RW_Meta_Box {

 // show uploaded images in 1 cell, overwrite original method
 function show_field_image($field, $meta) {
  global $post;

  echo "<td colspan='2'>{$field['name']}<br />";

  // show attached images
  $attachs = get_posts(array(
   'numberposts' => -1,
   'post_type' => 'attachment',
   'post_parent' => $post->ID,
   'post_mime_type' => 'image', // get attached images only
   'output' => ARRAY_A
  ));
  if (!empty($attachs)) {
   $nonce = wp_create_nonce('rw_ajax_delete_file');

   echo '<div style="margin-bottom: 10px"><strong>' . _('Images attached to this post') . '</strong></div>';
   foreach ($attachs as $att) {
    $src = wp_get_attachment_image_src($att->ID, 'thumbnail');
    $src = $src[0];
    echo "<div style='margin: 0 10px 10px 0; float: left'><img width='150' src='$src' /><br />
      <a class='rw-delete-file' href='javascript:void(0)' rel='{$att->ID}-{$nonce}'>Delete</a>
     </div>";
   }
  }

  // show form upload
  echo "<div style='clear: both'><strong>" . _('Upload new images') . "</strong></div>
   <div class='new-files'>
    <div class='file-input'><input type='file' name='{$field['id']}[]' /></div>
    <a class='rw-add-file' href='javascript:void(0)'>" . _('Add more image') . "</a>
   </div>
  </td>";
 }

Easily to contribute

The idea of separating methods came to me when I saw the way our contributors added features to the class. All of them have to change code directly. So, each developer has his own version of the script, and all the works of combining them falls down on my shoulders. It's hard, yes, and buggy because I'm not sure if there's no errors while doing it.

So, with this version, I hope all developers have a basic solid and reliable fundamental, that you can sit on and do all the extending works without worrying about other people. Perhaps each of you can have an (or many) extended class, but it will be very easy to share it with other developers. They don't have to look into every line of code to find where you changed.

And I hope you will contribute your extended classes here in the comments, and maybe in the next version, I'll release them as modules to give ability plug-and-play to users.

Added some new field types

In response to many requests of supporting new field types, I added these fields in this version:
- date, time, color with the picker, of course. I use jQueryUI at Google CDN, and the timepicker addon by Trent Richardson.
- checkbox list, credit to Jan Fabry.
- taxonomy was added as an example of extending the class, credit to Manny Fresh.

Each new types have some options that you should read in the meta-box-usage.php file in the download package. I left many comments in this file that I believed you can understand without any efforts.

Meta Box Script Update V3.0

Added some features for old field types

There're some slightly changes for old types, such as:
- change the way of definitions of options for radio, select fields to make it simpler and more appropriate.
- add multiple option for select field, allow users select multiple options.
- show uploaded files as well as allow users add/delete attached files
- delete attached files when post is deleted (credit to Kai)

And the validation function MUST return field value instead of boolean value.

Code bug fixes and improvements

There were some bugs in old code that show warnings when turn on debug mode in WordPress by define('WP_DEBUG', true); in wp-config.php file.

Some code were also changed to make it shorter and more clearly.

How to show custom meta fields on website?

This basic question is asked many times. And I'm sorry to not writing this at the beginning of the series.

Get value of field with single value

Most fields have single value (this is the default option). To get the value of field, use this code:

$meta = get_post_meta(get_the_ID(), 'meta_key', true);
echo $meta; // if you want to show

The last parameter true indicates that our field has single value.

The meta_key is the ID of meta field that has been registered. For example, if you registered a field with:

$prefix = 'rw_';
...
array(
 'name' => 'Full name',
 'id' => $prefix . 'fname',
 'type' => 'text'
)

Then meta_key is rw_fname. Note that it is prefixed.

For more information about get_post_meta(); please read the Codex.

Get value of field with multiple values

There're some fields that may have multiple values such as select, checkbox_list. To get (or check) values of these fields, use this code:

$metas = get_post_meta(get_the_ID(), 'meta_key', false);

// if you want to show values
foreach ($metas as $meta) {
 echo $meta;
}

// if you want to check if a value $val is set or not
if (in_array($val, $metas)) {
 echo "$val is set";
} else {
 echo "$val is not set";
}

The code is very similar to the one above. The different is the last parameter, which now is false, that means our field doesn't have single value (ie it has multiple values).

Get uploaded files

Updated: Since version 3.0.1, uploaded files' urls are saved as a field with multiple values. So, you can use the code for getting field with multiple values above. The old code below still works, but it will get all attached files to this post (maybe there're some files you uploaded in the editor, not in the meta box).

To get uploaded files of a post, use this code:

$attachs = get_posts(array(
 'post_type' => 'attachment',
 'post_parent' => get_the_ID(),
 'numberposts' => -1
));
if (!empty($attachs)) {
 foreach ($attachs as $att) {
  if (wp_attachment_is_image($att->ID)) continue; // don't show attached images

  echo '<p>' . wp_get_attachment_link($att->ID) . '</p>';
 }
}

This code will show links to each uploaded files using wp_get_attachment_link(); function.

There're various functions at the Codex for attachments that you might be interested in.

Get uploaded images

Updated: Since version 3.0.1, uploaded images' urls are saved as a field with multiple values like uploaded files. So, you can use the code for getting field with multiple values above. The old code below still works, but it will get all attached images to this post (maybe there're some images you uploaded in the editor, not in the meta box).

To get (and show) uploaded images, use this code:

$attachs = get_posts(array(
 'numberposts' => -1,
 'post_type' => 'attachment',
 'post_parent' => get_the_ID(),
 'post_mime_type' => 'image', // get attached images only
 'output' => ARRAY_A
));
if (!empty($attachs)) {
 foreach ($attachs as $att) {
  // get image's source based on size, can be 'thumbnail', 'medium', 'large', 'full' or registed post thumbnails sizes
  $src = wp_get_attachment_image_src($att->ID, 'full');
  $src = $src[0];

  // show image
  echo "<div style='margin: 0 10px 10px 0; float: left'><img src='$src' /></div>";
 }
}

This code will show all attached images to the post.

A short way to do this is use the [gallery] shortcode. It is a built-in WordPress shortcode that you can use immediately. For more information about this shortcode, please read the Codex.

Another way to achieve this is using a plugin. A famous plugin for getting image of post is Get The Image, written by Justin Tadlock. It has many options and easy to use.

Hope this guide help you when using the Meta Box script.

This post is the first part of meta box series:

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

PS: we'll drop lifetime pricing from Dec 01, 2024. Get it now before it's gone!

Leave a Reply

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


Copyright © 2024 Deluxe Blog Tips. All rights reserved.

My products: Meta Box | Slim SEO