Custom attributes for inputs

Since version 4.7 of Meta Box, users can add custom attributes for inputs like text, URL, email fields. This feature is very helpful if developers want to add HTML5 attributes or something like data-* attribute for their custom JS code.

To add custom attributes to the fields, just define them as a 'key' => 'value' like this:

'attributes' => array(
    'disabled'  => true,
    'minlength' => 10,
),

If you want to add custom data-* attribute, you can add like this:

'attributes' => array(
    // Simple value
    'data-option1'  => 'value1',
    // Array of values
    'data-option2'  => json_encode( array( 'key1' => 'value1', 'key2' => 'value2' ) ),
),

Currently, this feature is supported in field text, url, email, checkbox, radio, date, time, datetime field.

Common attributes disabled, required, readonly, maxlength and pattern are also registered to be used as global parameters for fields, so you can use both these ways below as they are the same:

'attributes' => array(
    'disabled'  => true,
    'required'  => true,
    'readonly'  => true,
    'maxlength' => true,
    'pattern'   => true,
),

// or simpler, e.g. without wrapping inside 'attributes'

'disabled'  => true,
'required'  => true,
'readonly'  => true,
'maxlength' => true,
'pattern'   => true,

Shortcode

You can use[rwmb_meta]shortcode built in Meta Box plugin to deal with the problem of inserting values of custom fields in post content without opening theme files and inserting PHP code.

The shortcode take the following attributes:

[rwmb_meta post_id="15" meta_key="field_id" type="image" size="thumbnail" ...]

The [rwmb_meta] shortcode works exactly like rwmb_meta function (look at this documentation). All attributes are the same.

Shortcode attributes

AttributeDescription
post_idThe post ID. Optional. If not defined, then the ID of current post is used.
meta_keyThe meta key, same as field ID. Required.
typeField type. Default is text. You can bypass this attribute if your field has single value (e.g. not multiple, not clone). Required for field which is multiple or clone (checkbox_list, file and image fields, taxonomy, etc.).
multipleIf field has multiple values (like select with multiple selections), set this argument to true. It’s automatically set to true for checkbox_list, file and image fields.
sizeImage size, used for image fields only. If not present, the thumbnail size will be used.
taxonomyThe taxonomy for which to retrieve terms, used for taxonomy fields.

Validation

The Meta Box plugin has built-in validation module for all fields. You can use validation to make a field required, check password length, check phone number format, etc.

Technical note:
The validation module is built with the popular jQuery validation plugin which makes simple client side form validation easy, whilst still offering plenty of customization options. The plugin comes bundled with a useful set of validation methods, while providing an API to write your own methods. All bundled methods come with default error messages in English and translations into 37 other languages.

How to set validation rules

To start using validation in Meta Box, you need to add an attribute validation to your meta box array. This attribute has a parameter rules (associated array) for validation rules. Each element of this parameter is a set of rules for one field.

Let’s look at the example:

'validation' => array(
    'rules'    => array(
        "{$prefix}password" => array(
            'required'  => true,
            'minlength' => 7,
            // More rules here
        ),
        // Rules for other fields
    ),
)

This example add validation for "{$prefix}password" field (this is the ID of the field which is prefixed). There are 2 validation rules for this field: field is required and minimum length is 7.

So, basically the format for rules is:

'rules' => array(
    'field_id_1' => array(
         // rules for field_id_1
    ),
    'field_id_2' => array(
         // rules for field_id_2
    ),
    // Rules for other fields
),

List of built-in validation rules

These are list of basic validation rules that you can use for your fields:

NameDescription
requiredMakes the element required.
minlengthMakes the element require a given minimum length.
maxlengthMakes the element require a given maxmimum length.
rangelengthMakes the element require a given value range. Array.
minMakes the element require a given minimum.
maxMakes the element require a given maximum.
rangeMakes the element require a given value range. Array.
emailMakes the element require a valid email
urlMakes the element require a valid url
dateMakes the element require a date.
dateISOMakes the element require an ISO date.
numberMakes the element require a decimal number.
digitsMakes the element require digits only.
creditcardMakes the element require a credit card number.
equalToRequires the element to be the same as another one. Value must be the ID of another field.
remoteRequests a resource to check the element for validity. Value can be URL of the resource to request for server side validation (string) or options to fully customize the request, see jQuery.ajax. The server side resource is called via jQuery.ajax and gets a key/value pair corresponding to the name of the validated element and its value as a GET parameter. The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. “That name is already taken, try peter123 instead” to display as the error message.

For more details about validation rules, please read the documentation page of jQuery validation plugin.

Error messages

To use custom error messages, you can add another parameter messages for validation attribute. This parameter has the same format as rules, but it just contains error messages for each rule.

Look at the example below:

'validation' => array(
    'rules'    => array(
        "{$prefix}password" => array(
            'required'  => true,
            'minlength' => 7,
        ),
    ),
    // Optional override of default error messages
    'messages' => array(
        "{$prefix}password" => array(
            'required'  => __( 'Password is required', 'your-prefix' ),
            'minlength' => __( 'Password must be at least 7 characters', 'your-prefix' ),
        ),
    )
)

Repeating fields

The repeating feature of the Meta Box plugin allows us to create multiple inputs from a text, textarea, select, … fields without declaring many fields in the code.

To make a field cloneable, just add 'clone' => true to field’s parameter. After doing that, you’ll see a new + (Add Clone) button below field input:

add clone

Clicking on that button will duplicate field input:

duplicate input

You can notice that there are new buttons (Remove Clone) which allow you to remove clones.

Since version 4.5.4, there’re 2 additional parameters which allow you to use clone feature better:

  1.  max_clone: limit the number of clones. Integer. Must be greater than 2. Optional.
  2. sort_clone: allow users to drag-and-drop sort clones. Boolean, true to enable sorting, false to disable. Default is false. See the following screenshot.

drag and drop

Include Meta Box Plugin In Themes/Plugins

Using TGM Activation Class

It’s highly recommended not to include the plugin directly inside a WordPress theme or plugin. Including the plugin inside a theme or plugin can lead to potential problems such as:

  • The plugin is being already installed on website
  • Maybe the plugin is included in another plugin. In this case, we can’t be sure which version of the plugin is used and that can break the website (see this discussion)

To avoid these problems, it’s highly recommended using TGM Activation Class to tell users that your theme/plugin needs the Meta Box plugin to run properly. This class is easy to use and configure (just follow the instruction at its homepage – simply copy and paste with small changes such as plugin name and slug).

This is the sample code:

https://gist.github.com/rilwis/30d42fe624320653cb71

Include Meta Box directly

Since version 4.8.0, including the Meta Box plugin directly in themes or plugins is much easier and safer than before. The version 4.8.0+ introduces a new way of loading plugin files, which is compatible with any theme and plugin.

Note: Although the method described here works, it’s still highly recommended to use TGM Activation Class to avoid potential compatibility problems.

In order to include the Meta Box plugin into your theme or plugin, please follow the following steps:

  1. Copy the plugin folder meta-box to your theme. It doesn’t matter if you put it in the theme root folder or in a subfolder.
  2. Include the plugin’s main file by putting the following line into the functions.php of your theme or your plugin’s file:
require get_template_directory() . '/meta-box/meta-box.php'; // Path to the plugin's main file

Prior to version 4.8.0, you have to define some constants for the Meta Box plugin before include the plugin’s main file:

define( 'RWMB_DIR', get_template_directory() . '/meta-box/' );
define( 'RWMB_URL', get_template_directory_uri() . '/meta-box/' );
require RWMB_DIR . 'meta-box.php';

Display map in the front end

To display map field in the frontend, we still use rwmb_meta function (see this docs), but we need to add more parameters. Assume we have a map field with id=loc, this is how we display map:

$args = array(
    'type'         => 'map',
    'width'        => '640px', // Map width, default is 640px. Can be '%' or 'px'
    'height'       => '480px', // Map height, default is 480px. Can be '%' or 'px'
    'zoom'         => 14,  // Map zoom, default is the value set in admin, and if it's omitted - 14
    'marker'       => true, // Display marker? Default is 'true',
    'marker_title' => '', // Marker title when hover
    'info_window'  => '<h3>Info Window Title</h3>Info window content. HTML <strong>allowed</strong>', // Info window content, can be anything. HTML allowed.
);
echo rwmb_meta( 'loc', $args ); // For current post
echo rwmb_meta( 'loc', $args, $post_id ); // For another post with $post_id

All the arguments are self-explained.

A good thing here is you can add HTML to info_window. In the example above, I wrap the title into h3 tag, but you can put anything there. Just remember the content will be passed to Javascript, so things like quotes (single or double) should be avoided. You should use plain tags like strong, em, h2, h3, h4, … and style them by CSS.

If you need more advanced options for the map, use the js_options parameter, which accept an array of arguments from Google Maps API. For example:

$args = array(
    'type'         => 'map',
    'width'        => '640px',
    'height'       => '480px',
    'js_options'   => array(
        'mapTypeId'   => 'HYBRID',
        'zoomControl' => false,
        'zoom'        => 10, // You can use 'zoom' inside 'js_options' or as a separated parameter
    )
);

You also can display multiple maps on the same page. The function is smart enough to assign different ID (in the form rwmb-map-canvas-$counter) to each map displayed.

Get custom field value and display in the front end

To get field meta value, use this function:

rwmb_meta( $field_id, $args = array(), $post_id = null );

To display field value in the frontend, just put the code below in your theme’s template file:

<?php echo rwmb_meta( $field_id, $args, $post_id ); ?>

You can omit $args and/or $post_id. In that case, the function will return simple value (for text, radio, select) for the current post in the loop.

Note: Since Meta Box 4.8.0, in order to make the helper function works properly in the front end, the code that registers meta boxes and custom fields must run in BOTH front end and admin area. E.g, avoid writing like this:

if ( is_admin() ) {
    add_filter( 'rwmb_meta_boxes', 'prefix_register_meta_boxes' );
    function prefix_register_meta_boxes() {
        // Code
    }
}

Instead, write this:

add_filter( 'rwmb_meta_boxes', 'prefix_register_meta_boxes' );
function prefix_register_meta_boxes() {
    // Code
}

Arguments

NameDescription
$field_idThe field ID.
$argsArray of arguments or a string in format param=value1&amp;param2=value2. See below for supported arguments.
$post_idPost ID. Optional. If not present, current post ID is used.

List of arguments for $args:

NameDescription
typeField type. Required for all fields for version prior to 4.8.0. Since 4.8.0, this is required only for map and oembed to display rich media.
multipleDoes field has multiple values (true or false)? For fields that always have multiple values (checkbox list, autocomplete, file, image) it’s automatically set to true and you can omit it. Not used since 4.8.0.
cloneIs field cloneable? Not used since 4.8.0.
taxonomyTaxonomy. Required for taxonomy and taxonomy_advanced for version prior to 4.8.0. See taxonomy field below for more info.
sizeImage size. Used for image fields only. If missed, thumbnail will be used. See image field below for more info

Returned value

  • If the field has a single value (not multiple, not clone), then the function returns the value of the field.
  • If the field has multiple values (multiple or clone), then the function returns an array of values.

This is an example how to display date of birth (which is a date field):

echo rwmb_meta( 'dob' );

This is an example how to display list of interests (a checkbox_list field):

$interests = rwmb_meta( 'interests' ); // Since 4.8.0
$interests = rwmb_meta( 'interests', 'type=checkbox_list' ); // Prior to 4.8.0

echo implode( ', ', $interests );

For specific field types, please see below:

File

For file, file_advanced, file_upload, the function accepts the following parameters in $args:

NameDescription
limitLimit the number of returned files.

The helper function function returns an array of files, each file has the following information:

array(
    'ID'   => 123,
    'name' => 'intro.txt',
    'path' => '/var/www/wp-content/uploads/intro.txt',
    'url' => 'http://example.com/wp-content/uploads/intro.txt',
    'title' => 'Introduction',
);

This is an example how to display links to download uploaded files:

$files = rwmb_meta( 'info' ); // Since 4.8.0
$files = rwmb_meta( 'info', 'type=file' ); // Prior to 4.8.0

if ( !empty( $files ) ) {
    foreach ( $files as $file ) {
        echo "<a title="{$file['name']}" href="{$file['url']}">{$file['name']}</a>";
    }
}

Image

For image, image_advanced, plupload_image, thickbox_image fields, the function accepts the following parameters in $args:

NameDescription
sizeImage size returned. Optional. If missed, thumbnail will be used.
limitLimit the number of returned images.

The function returns an array of images, each image has the following information:

array(
    'ID'   => 123,
    'name' => 'logo-150x80.png',
    'path' => '/var/www/wp-content/uploads/logo-150x80.png',
    'url' => 'http://example.com/wp-content/uploads/logo-150x80.png',
    'width' => 150,
    'height' => 80,
    'full_url' => 'http://example.com/wp-content/uploads/logo.png',
    'title' => 'Logo',
    'caption' => 'Logo caption',
    'description' => 'Used in the header',
    'alt' => 'Logo ALT text',
    'srcset' => 'large.jpg 1920w, medium.jpg 960w, small.jpg 480w' // List of responsive image src, added in 4.8.0
    'sizes' => array(), // List of image sizes. See http://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata
    'image_meta' => array(), // List of image meta. See http://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata
)

There’s one argument in the returned array that you might be interested in: full_url. It’s the URL of the full-size image (original image). You can use it for lightbox effect or in a slider with thumbnails.

This is an example how to Display uploaded images with lightbox effect:

$images = rwmb_meta( 'gallery', 'size=YOURSIZE' ); // Since 4.8.0
$images = rwmb_meta( 'gallery', 'type=image&size=YOURSIZE' ); // Prior to 4.8.0

if ( !empty( $images ) ) {
    foreach ( $images as $image ) {
        echo '<a href="', esc_url( $image['full_url'] ), '" title="', esc_attr( $image['title'] ), '" rel="lightbox"><img style="padding:5px" src="', esc_url( $image['url'] ), '"  alt="', esc_attr( $image['alt'] ), '"></a>';
    }
}

Map

For map, the function accepts the following parameters in $args:

$args = array(
    'type' => 'map', // Required
    'width' => '640px', // Map width, default is 640px. Can be '%' or 'px'
    'height' => '480px', // Map height, default is 480px. Can be '%' or 'px'
    'zoom' => 14, // Map zoom, default is the value set in admin, and if it's omitted - 14
    'marker' => true, // Display marker? Default is 'true',
    'marker_title' => '', // Marker title when hover
    'marker_icon' => '', // URL to the custom marker icon. If missed, use default icon.
    'info_window' => '<h3>Info Window Title</h3>Info window content. HTML <strong>allowed</strong>', // Info window content, can be anything. HTML allowed.
    'js_options' => array()
);

All the arguments are self-explained.

A good thing here is you can add HTML to info_window. Just remember the content will be passed to Javascript, so things like quotes (single or double) should be avoided. You should use plain tags like strong, em, h2, h3, h4, … and style them by CSS.

If you need more advanced options for the map, use the js_options parameter, which accept an array of arguments from Google Maps API. For example:

$args = array(
    'type' => 'map',
    'width' => '640px',
    'height' => '480px',
    'js_options' => array(
        'mapTypeId' => 'HYBRID',
        'zoomControl' => false,
        'zoom' => 10, // You can use 'zoom' inside 'js_options' or as a separated parameter
    ),
);

Note: The function returns the HTML markup for the map, NOT the value stored in the custom field.

To display the map, simply use the code below:

echo rwmb_meta( 'field_id', $args );

To get the value stored in the custom field, please use the code below:

$location = get_post_meta( get_the_ID(), 'field_id', true );
// returns "latitude,longitude,zoom"

Oembed

For oembed field, the helper function returns the rendered HTML markup for the object (video, audio, etc.). In order to show the HTML, you must set type=oembed in the $args as follow

echo rwmb_meta( 'field_id', 'type=oembed' );

To get the value stored in the custom field, e.g. the URL of the oembed object, please use the code below:

$url = get_post_meta( get_the_ID(), 'field_id', true );
// returns "http://youtube.com/watch?v=abcXYZ"

Post

For post field, the helper function returns post ID.

Taxonomy

For taxonomy and taxonomy_advanced field, the helper function returns list of terms object, similar to get_terms function.

Note: Prior to 4.8.0, you must set type=taxonomy&amp;taxonomy=TAXONOMY in $args to make it work properly.

This example shows how to display list of terms:

$terms = rwmb_meta( 'field_id' );
$content = '';
if ( !empty( $terms ) ) {
    $content .= '<ul>';
    foreach ( $terms as $term ) {
        $content .= sprintf(
            '<li><a title="%s" href="%s">%s</a></li>',
            esc_attr( $term->name ),
            esc_url( get_term_link( $term, 'tax_slug' ) ),
            esc_html( $term->name )
        );
    }
}
echo $content;

User

For user field, the helper function returns user ID.

WYSIWYG

The WYSIWYG field only displays the raw content in HTML format. It doesn’t wrap paragraphs in p tag by default or render shortcodes as in the the_content() function. To do that, you need to use the following code:

$content = rwmb_meta( 'field_id' );
$content = wpautop( $content ); // Wrap paragraphs in p tags
$content = do_shortcode( $content ); // Render shortcodes
echo $content;

// Short version
echo do_shortcode( wpautop( rwmb_meta( 'field_id' ) ) );

Prevent undefined function rwmb_meta

If you’re using rwmb_meta in your theme, there may be a situation when an admin accidentally deactivate the Meta Box plugin and you will see error “Undefined function rwmb_meta…” and your site will be broken.

To prevent this problem, a simple fix for that is adding the following code into your theme’s functions.php file:

if ( ! function_exists( 'rwmb_meta' ) ) {
    function rwmb_meta( $key, $args = '', $post_id = null ) {
        return false;
    }
}

For developers

The rwmb_meta function is just a wrapper of get_post_meta with some additions to match the way the plugin saves post meta in the database. It also adds some additional information to the returned value (such as image info) to make it’s easier for users.

However, you can always use get_post_meta to get the value stored in the custom fields. print_r might help you to see how the value is stored in the database.

Define Fields

Each field in a meta box is an array of its own attributes.

Common field attributes

Each field of a meta box can have the following attributes:

AttributeDescription
nameName of the custom field. It’ll be displayed in the meta box. Optional. Without name, the field input is 100% width.
idID of the field. Required. Must be unique. It will be used as meta_key. It’s a good practice to use only numbers, letters, and underscores.
typeField type. See the list below for all supported field types. Required.
desca short description explaining what it is. Optional.
stdDefault value of the custom field. Optional.
multipleDoes the field have multiple values (like the select field)? Optional. Default false.
classCustom CSS class, in case you want to style the field the way you want. Optional.
beforeCustom HTML outputted before field’s HTML
afterCustom HTML outputted after field’s HTML
cloneIs the field clonable? true or false. Optional. Since 4.8.3 it works for all field types, including file, image and wysiwyg.
max_cloneMaximum number of clones. Default 0 (unlimited).
sort_cloneAbility to drag-and-drop reorder clones (true or false). Optional. Default false.
add_buttonThe text for add more clone button. Optional. Default “+ Add more”.
attributesCustom attributes for inputs. See more details.

List of supported field type

This is the list of all supported field types in the Meta Box plugin with brief description:

Field TypeDescription
autocompleteText input that uses jQuery autocomplete library to perform the autocomplete action. Added in version 4.4.0.
buttonDisplay simple button. Usually used for JavaScript trigger
checkboxCheckbox
checkbox_listList of checkboxes
colorColor picker
custom_htmlOutput custom HTML content
dateDate picker
datetimeDate and time picker
dividerSimple horizontal line
emailEmail input using HTML 5 input with type="email"
fieldset_textGroup of text inputs
fileSimple file upload with default UI like <input type="file" />.
file_advancedAdvanced file upload with UI like WordPress media upload popup. Inherits file.
file_inputAllow to enter URL for a file or select a file from media library (UI like WordPress media upload popup). This field saves file URL as meta value.
file_uploadFile upload field, support drag and drop files. Inherits from media.
headingHeading text
hiddenInput field with hidden type
imageSimilar to file but used for images only. Allow drag and drop to reorder images. Inherits file.
image_advancedSimilar to file_advanced, but used for images only. Inherits file_advanced.
image_selectSimilar to radio select, but use images instead of “radio”
image_upload or plupload_imageImage upload field, support drag and drop files. Inherits image_advanced.
key_valueAdd an unlimited group of key-value pairs inputs
mapGoogle maps field
numberInput for numbers which uses new HTML5 input type="number"
oembedInput for videos, audios from Youtube, Vimeo and all supported sites by WordPress. It has a preview feature.
passwordPassword input field
postSelect post from select dropdown. Support custom post types. Inherits options from select or select_advanced based on field_type parameter
radioRadio input
rangeHTML 5 range input
selectSelect dropdown
select_advancedBeautiful select dropdown using select2 library. Inherits select
sliderjQuery UI slider field
taxonomySelect taxonomies. Has various options to display as check box list, select dropdown (supports simple select and select_advanced UI), tree (select parent taxonomy will show children taxonomies). Note: this field doesn’t save term IDs in post meta, instead of that, it only set post terms.
taxonomy_advancedSame as taxonomy but saves term IDs in post meta as a comma separated string. It doesn’t set post terms.
textText field
text_listGroup of text inputs. Similar to fieldset_text.
textareaTextarea field
thickbox_imageOld image upload using Thickbox. Deprecated.
timeTime picker
urlHTML 5 URL input
userSelect dropdown for user, supports simple select and select_advanced UI
videoUpload or select a video from the Media Library using the WordPress media popup. Supports video preview and multiple uploads.
wysiwygWordPress editor field

Attributes for specific field types

Besides all common attributes, each field type can have other attributes. This section will describe all attributes for specific field types.

Important: The inherited fields can have attributes from their parents.

To understand the field hierarchy, please see this image.

We already prepared snippets for all field types. You can save time by just copy-and-paste from this link.

Autocomplete

AttributeDescription
optionsarray of predefined 'value' => 'Label' pairs. They’re used to autocomplete from user input. value is stored in the custom field. Required.
sizeinput size. Default 30. Optional.
cloneallow this field to be cloned? true or false (default). Optional.

Note: this field can store multiple values from user inputs

Checkbox list

AttributeDescription
optionsarray of 'value' => 'Label' pairs. value is stored in the custom field and Label is used to display in the meta box.

Color

AttributeDescription
alpha_channelWhether to add opacity to the color picker. true or false (default). Optional.
js_optionsArray of color picker options. See full list of option on the Iris project page.

Custom HTML

AttributeDescription
stdThe custom HTML content which is displayed. Optional.
callbackThe PHP callback function that shows the content (if std is not used). Optional. Using PHP callback allows you to access to WordPress’s data such as current post, post content, current user, etc.

Date

AttributeDescription
sizesize of the input box. Optional. Default 10.
inlinedisplay the date picker inline with the input, true or false? Optional. Default false.
js_optionsjQuery date picker options. See here, some main options are:
dateFormat: Date format. Optional. Default yy-mm-dd. For the full list of date format, please see here. Note: The format option is deprecated and replaced by this option.
showButtonPanel | Show button panel or not? Optional. Default true.
timestampsave datetime in Unix timestamp format (but still display in human-readable format), true or false. Optional. Default false.

(See demo/date-time-js-options.php for example).

Datetime

AttributeDescription
sizesize of the input box. Optional. Default 20.
inlinedisplay the date picker inline with the input? Optional. Default false.
js_optionsa combination of date options and time options for jQuery. See date and time fields above.
timestampsave datetime in Unix timestamp format (but still display in human-readable format), true or false. Optional. Default false.

File

AttributeDescription
max_file_uploadsMax number of uploaded files. Optional.
force_deleteWhether or not delete the files from Media Library when deleting them from post meta (true or false)? Optional. Default false.

File Advanced – File Upload

AttributeDescription
max_file_uploadsMax number of uploaded files. Optional.
mime_typeMime type of files which we want to show in Media Library. Note: this is a filter to list items in Media popup, it doesn’t restrict file types when upload.
max_statusWhether to show the status of number of uploaded files when max_file_uploads is defined (xx/xx files uploaded). Optional. Default true.
max_file_sizeMaximum file size that the user can upload, in bytes. Optionally supports b, kb, mb, gb, tb suffixes. e.g. “10mb” or “1gb”.
force_deleteWhether or not delete the files from Media Library when deleting them from post meta (true or false)? Optional. Default false.

Image Advanced – Image Upload

AttributeDescription
max_file_uploadsMax number of uploaded files. Optional.
image_sizeThe image size to show in the admin.
mime_typeMime type of files which we want to show in Media Library. Note: this is a filter to list items in Media popup, it doesn’t restrict file types when upload.
max_statusWhether to show the status of number of uploaded files when max_file_uploads is defined (xx/xx files uploaded). Optional. Default true.
max_file_sizeMaximum file size that the user can upload, in bytes. Optionally supports b, kb, mb, gb, tb suffixes. e.g. “10mb” or “1gb”.
force_deleteWhether or not delete the files from Media Library when deleting them from post meta (true or false)? Optional. Default false.

Map

To register a map field, you need to actually register 2 fields:

  • 1 field with type text which stores the address of the map.
  • 1 field with type map. This field has the following attributes:
AttributeDescription
address_fieldThe ID of the text field above. Required.
stdThe initial position of the map and the marker in format latitude,longitude[,zoom] (zoom is optional). Optional.
api_keyThe Google Maps API key. This attribute is required since June 2016 and works in Meta Box 4.8.8+. Get the API key here.
regionThe region code, specified as a ccTLD (country code top-level domain). This parameter returns autocompleted address results influenced by the region (typically the country) from the address field. See here for more details.

See demo file.

Number

AttributeDescription
stepSet the increments at which a numeric value can be set. It can be the string any (for floating numbers) or a positive float number or integer. If this attribute is not set to any, the control accepts only values at multiples of the step value greater than the minimum. Default is 1. Optional.
minMinimum value. Optional.
maxMaximum value. Optional.
placeholderPlaceholder for the input field. Optional.

Post

AttributeDescription
post_typepost type where posts are get from
field_typehow to show posts, can be:
select: simple select box of items (default). Optional. If choosing this field type, then the field can have options from select field (such as placeholder).
select_tree: hierachical list of select boxes which allows to select multiple items (select/deselect parent item will show/hide child items)
select_advanced: beautiful select box using select2 library. If choosing this field type, then the field can have options from select_advanced field (such as placeholder), please check select_advanced field for full list of params.
checkbox_list: flatten list of checkboxes which allows to select multiple items
checkbox_tree: hierachical list of checkboxes which allows to select multiple items (select/deselect parent item will show/hide child items)
radio_list: list of flatten radio boxes which allows to select only 1 item
query_argsadditional query arguments, like in get_posts() function. Optional.

Radio

AttributeDescription
optionsarray of 'value' => 'Label' pairs. value is stored in the custom field and Label is used to display in the meta box.
inlineWhether to show all options in a line? Optional. Default is true.

Select

AttributeDescription
optionsarray of 'value' => 'Label' pairs. value is stored in the custom field and Label is used to display in the dropdown.
placeholderinstruction text for users to select value, like “Please select…”
multipleallow to select multiple values or not. Can be true or false. Optional. Default false.
select_all_nonewhether to show “Select: All | None” links that can help users select all options or clear selection. Used only when multiple is true. Optional. Default false.

Select Advanced

This field inherits all attributes from select field above and has more attributes as below:

AttributeDescription
js_optionsarray of options for select2 library. See this documentation for all options.

By default, Meta Box applies these default options for js_options:

AttributeDescription
allowClearAllow users to clear selection. Default true.
widthSet width by element’s width. Default resolve.
placeholderMake placeholder works just like select field. Default $field['placeholder'].

Taxonomy

AttributeDescription
taxonomyarray or string of taxonomy slug(s)
field_typehow to show taxonomy, can be:
select: simple select box of items (default). Optional. If choosing this field type, then the field can have options from select field (such as placeholder).
select_tree: hierachical list of select boxes which allows to select multiple items (select/deselect parent item will show/hide child items)
select_advanced: beautiful select box using select2 library. If choosing this field type, then the field can have options from select_advanced field (such as placeholder), please check select_advanced field for full list of params.
checkbox_list: flatten list of checkboxes which allows to select multiple items
checkbox_tree: hierachical list of checkboxes which allows to select multiple items (select/deselect parent item will show/hide child items)
radio_list: list of flatten radio boxes which allows to select only 1 item
query_argsadditional query arguments, like in get_terms() function. Optional.

Note: this field does NOT save term IDs in post meta, instead of that, it only set post terms.

Taxonomy Advanced

This field is exactly the same as taxonomy field, but it saves term IDs in post meta as a comma separated string. It does NOT set post terms.

Text

AttributeDescription
placeholderPlaceholder for the input box. Optional.
sizeSize of input box. Optional. Default 30.
datalistPredefined values that users can select from (users still can enter text if they want). Optional. This parameter has the following sub-parameters:
id: ID of the div that stores the options. Usually not used and auto-generated as {$field['id']_list. Useful if you have several text input with same datalist.
options: Array of predefined values to select from.

Textarea

AttributeDescription
colsnumber of columns. Optional. Default 60.
rowsnumber of rows. Optional. Default 4.

Text List

AttributeDescription
optionsArray of 'placeholder' => 'label' for the inputs.

Time

AttributeDescription
sizesize of input box. Optional. Default 10.
js_optionsjQuery date picker options. See here, some main options are:
timeFormat: Time format. Optional. Default hh:mm. For full list of time format, please see here. Note | The format option is deprecated and replaced by this option.
showButtonPanel: Show button panel or not? Optional. Default true.

(See demo/date-time-js-options.php for example).

User

AttributeDescription
field_typehow to show users, can be:
select: simple select box of items (default). Optional. If choosing this field type, then the field can have options from select field (such as placeholder).
select_advanced: beautiful select box using select2 library. If choosing this field type, then the field can have options from select_advanced field (such as placeholder), please check select_advanced field for full list of params.
checkbox_list: flatten list of checkboxes which allows to select multiple items
radio_list: list of flatten radio boxes which allows to select only 1 item
query_argsadditional query arguments, like in get_users() function. Optional.

Video

AttributeDescription
max_file_uploadsMax number of uploaded files. Optional.
force_deleteWhether or not delete the files from Media Library when deleting them from post meta (true or false)? Optional. Default false.

WYSIWYG (Editor)

AttributeDescription
rawIf you want to save data in raw format, e.g. exactly the same as you enter in the editor without applying wpautop() function. Value can be true or false (default). Optional.
optionsArray of editor options, which is the same as 3rd parameter for wp_editor() function. Please read the Codex for full descriptions of all options.

By default, the plugin uses 2 options:

AttributeDefault ValueDescription
editor_classrwmb-wysiwygJust to make CSS consistent with other fields
dfwtrueAllow to use “Distraction Free Writing” mode (full-screen mode)

Register Meta Boxes

To register meta boxes, copy and paste the code below into functions.php file of your theme or your plugin:

https://gist.github.com/rilwis/b733f20369b6c282e68f#file-register-meta-boxes-php

Filter

The Meta Box plugin uses rwmb_meta_boxes filter to register meta boxes. This is a custom filter which takes an array of defined meta boxes as the argument. The callback function must return an array of meta boxes.

Using filter prevents PHP errors if you accidentally forget to install or activate the Meta Box plugin. In that case, the code simply doesn’t run and doesn’t affect the rest of your website.

Prefix

In the beginning of the code, we defined a prefix for fields: $prefix = 'rw_';

It will be added before all of our custom field IDs. Using a prefix can prevent us from conflict with other scripts that also use custom fields.

Tips:

  • The prefix is optional. If you don’t want to use it, set it to an empty string or remove it (if you remove it, don’t forget to update id of fields).
  • Use underscore (_) at the beginning to make the custom fields hidden, e.g. they won’t show in the default WordPress Custom Fields meta box.
  • It’s a good practice to have an underscore (_) as last sign.

Meta Box Attributes

Each meta box has the following attributes:

NameDescription
idMeta box ID. Optional. If it’s absent, it will be generated from title using sanitize_title function.
titleMeta box title. Required.
post_typesCustom post types which the meta box is for. There can be an array of multiple custom post types or a string for the single post type. Must be in lowercase (like the slug). Optional. Default: post. This parameter is used instead of pages since version 4.4.1 (and fallback to pages for previous versions). See change log.
contextPart of the page where the meta box is displayed (normal, advanced or side). Optional. Default: normal.
priorityPriority within the context where the box is displayed (high or low). Optional. Default: high.
default_hiddenHide the meta box by default (true or false)? The meta box can be toggled using the checkbox option in screen Help (on the top right). Optional. Default false.
autosaveAuto save the custom fields’ values (like post content and title)? Optional. Default: false.
fieldsArray of fields. Each field is declared as an array with its parameters. To understand fields’ parameters, please read this documentation.

Historical note

Previously, you could register meta boxes using admin_init hook and a global variable as below:

https://gist.github.com/rilwis/b733f20369b6c282e68f#file-register-meta-boxes-deprecated-php

However, this method has some disadvantages:

  • You have to remember the plugin class name (RW_Meta_Box) to the check if it’s loaded or not which might be changed in the future.
  • If there is another code that uses the same global variable to register meta boxes, be careful that the global variable can be overwritten.
  • It works in the admin area only
  • It’s not compatible with some premium extensions such as Include Exclude, Settings Page, Term Meta.

Using rwmb_meta_boxes filter as described above, you will have more benefits:

  • The code is more elegant and easier to read.
  • There is no more global variable, so you never overwrite registered meta boxes by accident. If you want to edit or change existing meta boxes, there’s an instruction for you.
  • It’s compatible with all premium extensions.