MB Custom Table

Installation

Before installing the extension, you need to install Meta Box plugin first.

  1. Go to Plugins → Add New and search for Meta Box
  2. Click Install Now button to install the plugin
  3. After installing, click Activate Plugin to activate the plugin

The extension is just a WordPress plugin, you can install it like a normal WordPress plugin.

  1. Go to Plugins, click Add new, then click Upload plugin.
  2. Choose the .zip file you downloaded and click Install now
  3. After finishing upload, click Activate to finish.

Important: This extension requires Meta Box version 4.12.3+. If you’re using an older version of the plugin, please update.

Create a custom table

To create a custom table, you can do it manually by following this guide or using the API that the extension provides. The API simplifies the process and makes it easier for you.

This code creates a simple table for 3 custom fields (each custom field is a column):

MB_Custom_Table_API::create( 'my_custom_table', array(
    'address' => 'TEXT NOT NULL',
    'phone'   => 'TEXT NOT NULL',
    'email'   => 'TEXT NOT NULL',
) );

This will generate a SQL query for creating a custom table like this:

$sql = "CREATE TABLE my_custom_table (
  ID int(11) unsigned NOT NULL,
  addresss TEXT NOT NULL,
  phone TEXT NOT NULL,
  email TEXT NOT NULL
  PRIMARY KEY  (ID)
)";

Note that the ID column is automatically created. It’s used to store the object ID for future reference. Object ID can be post ID, user ID or term ID, depends on what meta type the table is used for.

If you want to set keys for columns, just add the 3rd parameter:

MB_Custom_Table_API::create( 'my_custom_table', array(
    'address' => 'TEXT NOT NULL',
    'phone'   => 'TEXT NOT NULL',
    'email'   => 'TEXT NOT NULL',
), array( 'email' ) );

Which generates:

$sql = "CREATE TABLE my_custom_table (
  ID int(11) unsigned NOT NULL,
  addresss TEXT NOT NULL,
  phone TEXT NOT NULL,
  email TEXT NOT NULL
  PRIMARY KEY  (ID)
  KEY email
)";

Parameters

The API function takes 3 parameters as follows:

MB_Custom_Table_API::create( $table_name, $columns, $keys = array() );

Where:

ParameterDescription
table_nameThe custom table name. Required.
columnsArray of table columns, where key is the column ID and value is the column definition (similar in SQL). Required.
keysArray of key column IDs. Optional.

Notes

A. Do not add ID column: The ID column is automatically added to the list of columns and set as primary key in the table. It’s used to store the object ID (post, user, term) for future reference.

B. The column IDs must match custom fields’ IDs.

C. The table name doesn’t contain WordPress table prefix. The extension do not put any constrains for you to define the table name. If you want to use WordPress table prefix, you can do like this:

global $wpdb;
MB_Custom_Table_API::create( "{$wpdb->prefix}my_custom_table", array(
    'address' => 'TEXT NOT NULL',
    'phone'   => 'TEXT NOT NULL',
    'email'   => 'TEXT NOT NULL',
) );

D. You should check for the class existence before running the function, like this:

if ( ! class_exists( 'MB_Custom_Table_API' ) ) {
    return;
}
MB_Custom_Table_API::create( 'my_custom_table', array(
    'address' => 'TEXT NOT NULL',
    'phone'   => 'TEXT NOT NULL',
    'email'   => 'TEXT NOT NULL',
), array( 'email' ) );

E. The extension uses WordPress recommended method to create custom table, which means if the table already exists, the code will do nothing. Although, it’s recommended to run the code that create custom tables only when activate your plugin, like this:

register_activation_hook( __FILE__, 'prefix_create_table' );
function prefix_create_table() {
    if ( ! class_exists( 'MB_Custom_Table_API' ) ) {
        return;
    }
    MB_Custom_Table_API::create( 'my_custom_table', array(
        'address' => 'TEXT NOT NULL',
        'phone'   => 'TEXT NOT NULL',
        'email'   => 'TEXT NOT NULL',
    ), array( 'email' ) );
}

But for some reason, if you can’t run the code when activate your plugin, it’s totally fine to run the code in init or plugins_loaded hook:

add_action( 'plugins_loaded', 'prefix_create_table' );
function prefix_create_table() {
    if ( ! class_exists( 'MB_Custom_Table_API' ) ) {
        return;
    }
    MB_Custom_Table_API::create( 'my_custom_table', array(
        'address' => 'TEXT NOT NULL',
        'phone'   => 'TEXT NOT NULL',
        'email'   => 'TEXT NOT NULL',
    ), array( 'email' ) );
}

Register meta boxes to use custom table

To tell a meta box to use custom table to store custom fields instead of default meta tables, you need to specify 2 parameters storage_type and table like this:

$meta_boxes[] = array(
    'title'        => __( 'Meta Box Title', 'textdomain' ),
    'storage_type' => 'custom_table',    // Important
    'table'        => 'your_table_name', // Your custom table name
    'fields'       => array(...)
);

Now you can go to edit post screen (or edit user profile if you use the meta box for user profile page) and save the post. You’ll see the data is saved in the new custom table instead of meta tables.

Get meta value

You can use the helper rwmb_meta function to get meta value, just like the same as for normal custom fields. The only difference is you need to specify the table name in the function call, like this:

$value = rwmb_meta( $field_id, array( 'storage_type' => 'custom_table', 'table' => $table_name ), $post_id );
print_r( $value );

Also note that the call to the custom table will be cached, e.g. if you call the helper function several times for the same $post_id, it will only query once. This technique will improve the database performance.

MB Revision

Installation

Before installing the extension, you need to install Meta Box plugin first.

  1. Go to Plugins → Add New and search for Meta Box
  2. Click Install Now button to install the plugin
  3. After installing, click Activate Plugin to activate the plugin

The extension is just a WordPress plugin, you can install it like a normal WordPress plugin.

  1. Go to Plugins, click Add new, then click Upload plugin.
  2. Choose the .zip file you downloaded and click Install now
  3. After finishing upload, click Activate to finish.

Important: This extension requires Meta Box version 4.12+. If you’re using an older version of the plugin, please update.

Enable revision support

First of all, please make sure that you didn’t turn off revision in WordPress. To check this, please open your wp-config.php and see if this line presents:

define( 'WP_POST_REVISIONS', false );

If you can’t find it, that means revision is turned on, which is great!

Now back to Meta Box. Please make sure you understand how to register meta boxes before continuing.

To enable revision support for a meta box, simply add a new parameter to the meta box as follows:

'revision' => true,

Now whenever you update a post, WordPress will create a revision for it. And MB Revision ensures all the values of the custom fields are copied from the parent post to that revision.

Compare the changes in each revision

When you update a post, WordPress automatically creates a revision for that post. You can see the list of revisions in the Revisions meta box below the main editor:

revision list

Also, in the Publish meta box, you’ll see a link to browse all revisions:

browse revision

Clicking either on any revision in the list or on Browse link brings you to the revision comparison screen. There you’ll see something like this:

revision compare

Except title and content, which are post fields, other items on this screen are custom fields created by Meta Box. There you’ll see highlighted lines or words, which are added or removed by users.

If the custom field has simple value (like a string), it will display fully here. If the custom field has structural value (array), it will display here as a JSON-encoded string. Using JSON allows you to see the values of each element in the array as well as the structure in general.

Please note that the extension works well with Meta Box Group extension.

Restore the revision

If you find out that the current version of the post is incorrect, you can compare it with the previous version and optionally restore it. In order to restore a revision, simply click on the Restore this revision button on the comparison screen.

MB Revision will copy values of the custom fields from the revision to the parent post. So your post will have the correct values of custom fields like it used to be.

Notes

Because WordPress supports revision for posts and custom post types only, the extension doesn’t work for term meta, user meta or settings pages.

Please make sure you either not define WP_POST_REVISIONS or set it to a proper value in wp-config.php. This constant disables or limits the number of revisions. Therefore, it might cause unexprected result. Please see WordPress Codex for more information.

Meta Box AIO

Meta Box AIO is a part of Developer Bundle, which contains all the premium extensions and the Updater extension. This extension allows you to just install 1 plugin and have everything in hand. See here for the introduction.

Settings Page

The extension has a settings page under Settings → Meta Box AIO, where you can enable/disable the modules you need/don’t need.

Meta Box AIO Settings Page
Meta Box AIO Settings Page

Simply check/uncheck the checkbox to enable/disable the corresponding extensions. Then click Save Changes.

Load Free Extensions From wordpress.org

Along with the premium extensions, Meta Box AIO allows you to load free extensions from wordpress.org. When activate the Meta Box AIO, you will see a notification at the top of the screen:

Meta Box AIO Notification
Meta Box AIO Notification

Simply click on the Begin installing plugins to install them (if you haven’t). And then click Begin activating plugins to activate them.

Filters

While the settings page and the notification to install free extensions are great for users, developers might want to hide them from normal users. To do that, Meta Box AIO provides some filters:

mb_aio_show_settings

This filter is used to show/hide the settings page. The callback function should return true to show the settings page, or false to hide it.

To hide the settings page, use the following code:

add_filter( 'mb_aio_show_settings', '__return_false' );

option_meta_box_aio

This filter allows you to change the option of the settings page. Thus, enable/disable modules by just coding.

For example, the code below enables only the Meta Box Builder extension:

add_filter( 'option_meta_box_aio', function( $option ) {
    $option = array( 'meta-box-builder' => 1 );
    return $option;
} );

The option is an array, where the extension slug is the key and value is 1 if enable, 0 if disable.

mb_aio_load_free_extensions

This filter allows you to show/hide notification to load free extensions from wordpress.org. The callback function should return true to show the settings page, or false to hide it.

To not load free extensions, use the following code:

add_filter( 'mb_aio_load_free_extensions', '__return_false' );

MB Frontend Submission

Installation

Before installing the extension, you need to install Meta Box plugin first.

  1. Go to Plugins → Add New and search for Meta Box
  2. Click Install Now button to install the plugin
  3. After installing, click Activate Plugin to activate the plugin

The extension is just a WordPress plugin, you can install it like a normal WordPress plugin.

  1. Go to Plugins, click Add new, then click Upload plugin.
  2. Choose the .zip file you downloaded and click Install now
  3. After finishing upload, click Activate to finish.

Important: This extension requires Meta Box version 4.11+. If you’re using an older version of the plugin, please update.

Create a frontend form

To create a frontend form, you need to register a meta box first. See this guide to do that. Don’t forget to set the meta box id. You need that to embed the form in the frontend.

Then you can show the form in the frontend using the following shortcode:

[mb_frontend_form id="Meta box ID"]

You can put the shortcode inside a page or post content to show it. If you want to embed the form using code, please use the following code:

$form = '[mb_frontend_form id="Meta box ID"]';
echo do_shortcode( $form );

Shortcode attributes

AttributesDescription
idMeta box ID. Required.
post_typeThe submitted post type. Optional. Default is the first post type defined in the meta box. If meta box is made for multiple post types, you should set this attribute to the correct one.
post_idThe post ID. Optional. Used only when you want to update an existing post.
post_statusThe status for submitted posts. See the list here.
post_fieldsList of post fields you want to show in the frontend, separated by comma. Supported following fields: title, content, excerpt, date, thumbnail.
submit_buttonThe text for the submit button.
confirmationThe text for the confirmation message when the form is successfully submitted.

Post template files

The plugin allows you to use a custom template files for post fields and the confirmation message (the fields defined by Meta Box is controlled by the Meta Box plugin and can’t be changed).

The plugin will look for a template file with the following order:

  • Inside a folder mb-frontend-submission of your child theme
  • Inside a folder mb-frontend-submission of your parent theme
  • In the plugin’s templates folder

In order to overwrite the output of post fields, please following the steps below:

  • Create a folder mb-frontend-submission in your theme.
  • Copy a template file that you want to change from plugins’s templates folder to the new mb-frontend-submission folder, keeping the same folder structure.
  • Modify the new template file.

Hooks

In order to allow developers to do other things when the form is submitted, we have created some actions and filters.

Post data filters

rwmb_frontend_insert_post_data

This filter is used to modify the submitted post data before it’s passed to the wp_insert_post function to create a new post. It accepts 1 parameter as the array of post data.

$data = apply_filters( 'rwmb_frontend_insert_post_data', $data );

rwmb_frontend_update_post_data

This filter is used to modify the submitted post data before it’s passed to the wp_update_post function to update an existing post. It accepts 1 parameter as the array of post data.

$data = apply_filters( 'rwmb_frontend_update_post_data', $data );

Post field filters

Sometimes you want to add more things to the post fields, such as make post title required, add description for post content, or even add a custom HTML before the post thumbnail. You can do that with the following post filter:

// Post title
$field = apply_filters( 'rwmb_frontend_post_title', array(
    'type' => 'text',
    'name' => esc_html__( 'Title', 'rwmb-frontend-submission' ),
    'id'   => 'post_title',
) );

// Post thumbnail
$field = apply_filters( 'rwmb_frontend_post_thumbnail', array(
    'type'             => 'image',
    'name'             => esc_html__( 'Thumbnail', 'rwmb-frontend-submission' ),
    'id'               => '_thumbnail_id',
    'max_file_uploads' => 1,
) );

// Post excerpt
$field   = apply_filters( 'rwmb_frontend_post_excerpt', array(
    'type' => 'textarea',
    'name' => esc_html__( 'Excerpt', 'rwmb-frontend-submission' ),
    'id'   => 'post_excerpt',
) );

// Post date
$field = apply_filters( 'rwmb_frontend_post_date', array(
    'type' => 'datetime',
    'name' => esc_html__( 'Date', 'rwmb-frontend-submission' ),
    'id'   => 'post_date',
) );

// Post content
$field   = apply_filters( 'rwmb_frontend_post_content', array(
    'type' => 'wysiwyg',
    'name' => esc_html__( 'Content', 'rwmb-frontend-submission' ),
    'id'   => 'post_content',
) );

Each post field is treated as a normal Meta Box field (see here for full list of field attributes).

So, to make the post title required, you can do like this:

add_filter( 'rwmb_frontend_post_title', function( $field ) {
    $field['required'] = true;
    return $field;
} );

Post actions

rwmb_frontend_after_save_post

This action fires after the post is created or updated. At that time, all the custom fields in the meta box are already saved into the post meta.

do_action( 'rwmb_frontend_after_save_post', $object );

The action accepts 1 parameter: the instance of the MB_Frontend_Post class, which handles the submission. It has the following public properties that you can use:

  • $post_type: The current post type
  • $post_id: The submitted post ID
  • $fields: The post fields
  • $config: The configuration, taken from the shortcode attributes

Form actions

rwmb_frontend_after_process

This action fires after the form is processed, e.g. saved or updated. It accepts one parameter $config – the form configuration, taken from the shortcode attributes.

You can use this action to do a custom redirect to your Thank you page or send an email notification.

add_action( 'rwmb_frontend_after_process', function( $config ) {
    if ( 'my-meta-box' === $config['id'] ) {
        wp_mail( 'admin@domain.com', 'New submission', 'A new post has been just submitted.' );

        wp_safe_redirect( 'thank-you' );
        die;
    }
} );

rwmb_frontend_before_display_confirmation

This action fires before the confirmation message is displayed. It accepts one parameter $config – the form configuration, taken from the shortcode attributes.

rwmb_frontend_after_display_confirmation

This action fires after the confirmation message is displayed. It accepts one parameter $config – the form configuration, taken from the shortcode attributes.

Notes

Upload files / images

To be able to upload files or images (via fields file_advanced, file_upload, image_advanced, image_upload), users have to login and proper capability upload_files to access the Media Library. If your users don’t have that capability (if they have subscriber role), then the upload fields don’t work. In that case, you can add the capability for that role as follows:

function mb_allow_subscriber_uploads() {
    if ( is_admin() ) {
        return;
    }

    // Replace 'subscriber' with the required role to update, can also be contributor.
    $subscriber = get_role( 'subscriber' );
    $subscriber->add_cap( 'upload_files' );
}
add_action( 'init', 'mb_allow_subscriber_uploads' );

Another solution is using file or image fields. Both of them works similar. They just don’t have a nice UI, but they do the job very well.

Styling

The extension outputs the default fields’ HTML with CSS comes from Meta Box plugin. The style is basic and works in most cases. However, to make it match perfectly with your theme’s style, you need to do some work with CSS.

Caching

As you might know, Meta Box uses nonces to prevent misuse or malicious requests. As the nonce fields are outputted directly in the HTML, they might be cached by caching plugins such as W3 Total Cache, WP Super Cache, etc. And thus, the verification of the nonce might not work properly and break the form submission. In this case, please do not cache the page where the form is embeded (both caching plugins allow you to do that). For more information, please read this technical article.

MB User Meta

Installation

Before installing the extension, you need to install Meta Box plugin first.

  1. Go to Plugins → Add New and search for Meta Box
  2. Click Install Now button to install the plugin
  3. After installing, click Activate Plugin to activate the plugin

The extension is just a WordPress plugin, you can install it like a normal WordPress plugin.

  1. Go to Plugins, click Add new, then click Upload plugin.
  2. Choose the .zip file you downloaded and click Install now
  3. After finishing upload, click Activate to finish.

Add custom fields to user profile

Registering custom fields for user is similar to posts. See this documentation to know how to register a meta box, and this documentation to know how to define fields.

The only difference here is when you register a meta box for user profile , you need to specify a parameter 'type' => 'user'. That’s all!

Example

The code below register 2 meta boxes (sections) for user profile:

https://gist.github.com/rilwis/afa4b6eabc99fd8b03a69deb127b4428#file-user-meta-php

Result:

User meta screenshot

Getting user meta value

Since version 1.1, you’re able to use helper function rwmb_meta to get user meta value.

$value = rwmb_meta( $field_id, array( 'object_type' => 'user' ), $user_id );
echo $value;

The code is very similar to get post meta. The differences are:

  • In the 2nd parameter, you need to pass 'object_type' => 'user', and
  • In the last parameter, you need to pass the user ID

Other parameters are the same as for post. Please see this documentation for details.

Manually retrieve value

User meta value is saved in a similar way as post meta. To get user meta value, use the function:

$meta = get_user_meta( $term_id, $field_id, true );
echo $meta;

// Or use this code if field has multiple value
$meta = get_user_meta( $term_id, $field_id, false );
if ( $meta ) {
    foreach ( $meta as $value ) {
        echo $value;
    }
}

Important Note:

The helper function returns only raw data of term meta value. It doesn’t return meaningful information for images, file, etc. To do that, please add a small piece of code as follow:

// Getting images
$image_ids = get_user_meta( $term_id, $field_id, false ); // Media fields are always multiple.
foreach ( $image_ids as $image_id ) {
    $image = RWMB_Image_Field::file_info( $image_id, array( 'size' => 'thumbnail' ) );
    echo '<img src="' . $image['url'] . '" width="' . $image['width'] . '" height="' . $image['height'] . '" />';
}

These are some helper function that you can use to retrieve more info:

Field typeHelper function(s)
image, image_advanced, plupload_image, thickbox_imagewp_get_attachment_image_src()
wp_get_attachment_image_url()
RWMB_Image_Field::file_info( $image_id, $args ); (where $args is an array and accepts only size attribute)
file, file_advancedget_attached_file()
RWMB_File_Field::file_info( $image_id );
oembedRWMB_OEmbed_Field::get_embed( $url );
taxonomy, taxonomy_advancedget_term()
userget_userdata()
postget_post()

To understand which “raw” value is saved for subfields, please read this documentation.

Meta Box Geolocation

Installation

Before installing the extension, you need to install Meta Box plugin first.

  1. Go to Plugins → Add New and search for Meta Box
  2. Click Install Now button to install the plugin
  3. After installing, click Activate Plugin to activate the plugin

The extension is just a WordPress plugin, you can install it like a normal WordPress plugin.

  1. Go to Plugins, click Add new, then click Upload plugin.
  2. Choose the .zip file you downloaded and click Install now
  3. After finishing upload, click Activate to finish.

Usage

Make sure you know how to register meta boxes and define fields before continuing!

Tell Meta Box that you’ll add Geolocation data.

For better performance, Geolocation is disabled by default, and of course, Meta Box doesn’t know when to load Meta Box Geolocation script and Google Maps API. So we will have to tell Meta Box to load those scripts first.

Add this line to your Meta Box (not field) array

'geo' => true

You can also add options to Geolocation. Which can contains these properties

  • An array of types specifies an explicit type or a type collection, as listed in the supported types below. If nothing is specified, all types are returned. In general, only a single type is allowed. The exception is that you can safely mix the geocode and establishment types, but note that this will have the same effect as specifying no types. The supported types are:
    • geocode instructs the Places service to return only geocoding results, rather than business results.
    • address instructs the Places service to return only geocoding results with a precise address.
    • establishment instructs the Places service to return only business results.
    • the (regions) type collection instructs the Places service to return any result matching the following types:
      • locality
      • sublocality
      • postal_code
      • country
      • administrative_area1
      • administrative_area2
    • the (cities) type collection instructs the Places service to return results that match either locality or administrative_area3.
  • bounds is a google.maps.LatLngBounds object specifying the area in which to search for places. The results are biased towards, but not restricted to, places contained within these bounds.

  • componentRestrictions can be used to restrict results to specific groups. Currently, you can use componentRestrictions to filter by country. The country must be passed as a two-character, ISO 3166-1 Alpha-2 compatible country code.

For more information, visit Google Autocomplete Options

To add options. Just pass an array of options to geo key instead of default 'geo' => true. For instance:

// Restrict the result in Australia only
'geo' => [
    'componentRestrictions' => [
        'country' => 'au'
    ]
]

// Return only business results
'geo' => [
    'types' => ['establishment']
],

// Return only cities and business results
'geo' => [
    'types' => ['(cities)', 'establishment']
],

Adding Auto Complete field

To add an auto complete field. Simply add a text field and set it id starts with address. Like address or address_something… The plugin will treat that field as auto complete address field.
You can add auto complete to textarea, it works but will generate warning messages.

Populate Field Data

Address Components

When you selected an address from Auto-Complete field. It returns an array of Address Component Types. Which you can use it to populate to other fields. The following types are supported by Google:

TypeDescription
street_addressindicates a precise street address.
routeindicates a named route (such as “US 101”).
intersectionindicates a major intersection, usually of two major roads.
politicalindicates a political entity. Usually, this type indicates a polygon of some civil administration.
countryindicates the national political entity and is typically the highest order type returned by the Geocoder.
administrative_area_level_1indicates a first-order civil entity below the country level. Within the United States, these administrative levels are states. Not all nations exhibit these administrative levels.
administrative_area_level_2indicates a second-order civil entity below the country level. Within the United States, these administrative levels are counties. Not all nations exhibit these administrative levels.
administrative_area_level_3indicates a third-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.
administrative_area_level_4indicates a fourth-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.
administrative_area_level_5indicates a fifth-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.
colloquial_areaindicates a commonly-used alternative name for the entity.
localityindicates an incorporated city or town political entity.
sublocalityindicates a first-order civil entity below a locality. For some locations may receive one of the additional types: sublocality_level_1 through to sublocality_level_5. Each sublocality|level is a civil entity. Larger numbers indicate a smaller geographic area.
neighborhoodindicates a named neighborhood.
premiseindicates a named location, usually a building or collection of buildings with a common name
subpremiseindicates the first-order entity below a named location, usually a singular building within a collection of buildings with a common name.
postal_codeindicates a postal code as used to address postal mail within the country.
natural_featureindicates a prominent natural feature.
airportindicates an airport.
parkindicates a named park.
post_boxindicates a specific postal box.
street_numberindicates the precise street number.
floorindicates the floor of a building address.
roomindicates the room of a building address.
latindicates latitude of the result
lngindicates longitude of the result
geometrysame as latitude,longitude
formatted_addressreturns human readable complete address
idunique id of current location
urlurl of current location

For more information about address components visit:
Google Address Component Types

Auto Populate

To auto populate data to the field. Just set that field’s ID same as one of Address Component Type above. For example, you create a number field with ID postal_code. The postal code type will auto populate to that field if exists.

Long name and Short Name
Let’s say we have a country named ‘Australia’. The long name is ‘Australia’ and short name is ‘AU’. And so on, if we have a state named ‘Queensland’, so ‘Queensland’ is the long name and ‘QLD’ is the short name.

By default, Meta Box Geolocation will populate the long name of the field. But you can use the short name by adding _short at the end of field id. For example: administrative_area_level_1_short, country_short

Binding Template

The power of Meta Box Geolocation is you can bind anything into a field. Let’s say we have a field with id dummy_field, this field id is not in Address Component Types list so by default the plugin won’t auto populate data to it. Now we’ll bind administrative_area_level_1 to that field. Just add

'binding' => 'administrative_area_level_1'

Example Result: Queensland

You can tell that field to use short version by prepending short: keyword

'binding' => 'short:administrative_area_level_1'

Example Result: QLD

You can also merge two fields, add any character you want to bind to that field. Like so:

'binding' => 'short:administrative_area_level_1 + " " + country'

Example Result: QLD Australia

Adding URL Params

By default, Google Geocoding API has the usage limit. See here. The free Google Geocoding API works in almost case but sometimes, you need to add API Key, or want to add custom params to URL. Just add a filter to gmap_api_params like so:

add_filter( 'gmap_api_params', function( $params ) {

$params['key'] = 'YOUR API KEY';

return $params;
});

Example

The plugin already ships with an example. You can browse it in examples/example.php.
https://gist.github.com/tanng/b626e45546223df55a24

Result
meta-box-geolocation

MB Admin Columns

Installation

Before installing the extension, you need to install Meta Box plugin first.

  1. Go to Plugins → Add New and search for Meta Box
  2. Click Install Now button to install the plugin
  3. After installing, click Activate Plugin to activate the plugin

The extension is just a WordPress plugin, you can install it like a normal WordPress plugin.

  1. Go to Plugins, click Add new, then click Upload plugin.
  2. Choose the .zip file you downloaded and click Install now
  3. After finishing upload, click Activate to finish.

Usage

Make sure you know how to register meta boxes and define fields before continuing!

To show the admin column for a custom field, simply add admin_columns parameter for that field. The parameter can be in one of 3 following formats (from the simple to advanced configuration):

1. Simply display the admin column

'admin_columns' => true,

This line tells the MB Admin Columns extension to display the meta value of the custom field in a custom column. This method uses the default configuration below:

  • The column title is field name
  • The column is added to the end of the table

2. Specify the column position

You can set the column in a specific position by one of the following rules:

'admin_columns' => 'before title',
'admin_columns' => 'after title',
'admin_columns' => 'replace title',

The format is 'admin_columns' => 'type column' where:

ParamDescription
typeMust be before, after or replace. Specify the position of the custom column.
before: Insert the column before an existing column
after: Insert the column after an existing column
replace: Replace an existing column by the new one
columnThe target existing column

Using this configuration, you are able to insert the custom column in any position you want. Note that the column title is the field name by default.

3. Advanced configuration

To add more rules for the custom column, you can declare admin_columns parameter as an array which accepts the following keys:

'admin_columns' => array(
    'position'   => 'after title',
    'title'      => __( 'Price', 'textdomain' ),
    'before'     => '$',
    'after'      => ' USD',
    'sort'       => true,
    'searchable' => true,
    'filterable' => false,
),

The meaning of keys are described below:

KeyDescription
positionSpecify where to insert the new column. Accept rule in the format 'type column'. It’s exactly the same as described in the #2 method above.
titleColumn title. Optional. Default is the field name.
beforeCustom HTML outputted before the column content. Optional.
afterCustom HTML outputted after the column content. Optional.
sortWhether to sort the column by meta value? Optional. Default is false.
searchableAllow to search posts by meta value. Optional. Default is false.
filterableAllow to filter posts by custom taxonomy. Applied only if the field is taxonomy field. Default is false.

Note that the sort parameter is used to sort displayed posts by altering the WordPress query. It works only with non-clonable and non-multiple fields.

Example

Assuming we have a custom post type ‘Book’ registered with the following code:

add_action( 'init', 'prefix_register_book_post_type' );
function prefix_register_book_post_type() {
    $labels = array(
        'name'          => _x( 'Books', 'Post Type General Name', 'textdomain' ),
        'singular_name' => _x( 'Book', 'Post Type Singular Name', 'textdomain' ),
        'menu_name'     => __( 'Book', 'textdomain' ),
    );
    $args   = array(
        'labels'     => $labels,
        'supports'   => array( 'title', 'editor', ),
        'public'     => true,
        'taxonomies' => array( 'category' ),
        'menu_icon'  => 'dashicons-book-alt',
    );
    register_post_type( 'book', $args );
}

Here is the code to register a meta box, custom fields with additional parameters for admin columns:

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

Here is the result:

Sample admin columns for Books
Sample admin columns for Books

Create custom admin columns without custom fields

By default, the extension is made to work with custom fields created by the Meta Box plugin. However, there are situations where you want to make it work with non-custom fields by Meta Box. And that’s totally possible. Follow the steps below (note that it requires some coding):

Step 1: Create a custom class for custom columns

Create a new file custom.php (you can name it anything you want) in your plugin / theme folder with the following content:

<?php
class Prefix_Custom_Admin_Columns extends MB_Admin_Columns_Post {
    public function columns( $columns ) {
        $columns  = parent::columns( $columns );
        $position = '';
        $target   = '';
        $this->add( $columns, 'column_id', 'Column Title', $position, $target );
        // Add more if you want
        return $columns;
    }
    public function show( $column, $post_id ) {
        switch ( $column ) {
            case 'column_id':
                echo 'Column content';
                break;
            // More columns
        }
    }
}

Note that the custom column(s) is added via the call $this->add( $columns, 'column_id', 'Column Title', $position, $target );. You can repeat that code to add as many column as you want.

In the show function, you must add code to display content of these columns.

Step 2: Create an instance of the class

In your plugin main file or functions.php of your theme, add the following code to create an instance of the class above:

add_action( 'admin_init', 'prefix_add_custom_columns', 20 );
function prefix_add_custom_columns() {
    require_once 'custom.php';
    new Prefix_Custom_Admin_Columns( 'post', array() );
}

Note that the call new Prefix_Custom_Admin_Columns( 'post', array() ); tells WordPress to add custom column(s) to post. You can change this to another post type if you want.

MB Term Meta

Installation

Before installing the extension, you need to install Meta Box plugin first.

  1. Go to Plugins → Add New and search for Meta Box
  2. Click Install Now button to install the plugin
  3. After installing, click Activate Plugin to activate the plugin

The extension is just a WordPress plugin, you can install it like a normal WordPress plugin.

  1. Go to Plugins, click Add new, then click Upload plugin.
  2. Choose the .zip file you downloaded and click Install now
  3. After finishing upload, click Activate to finish.

Add custom fields to terms

Registering custom meta boxes and custom fields for taxonomy is similar to posts. See this documentation to know how to register a meta box, and this documentation to know how to define fields.

The only difference here is when you register a meta box for a taxonomy, you need to specify a parameter taxonomies which the meta box will be added to. This parameter can be an array of taxonomy slugs or a string of single taxonomy slug. And you have to remove the parameter post_types.

Example

The code below register a meta box for category which has 4 custom fields:

https://gist.github.com/rilwis/689edb31a456419e02b0

Result:

Term meta screenshot

Getting term meta value

Using helper function

Since version 1.1, you’re able to use helper function rwmb_meta to get term meta value.

$value = rwmb_meta( $field_id, array( 'object_type' => 'term' ), $term_id );
echo $value;

The code is very similar to get post meta. The differences are:

  • In the 2nd parameter, you need to pass 'object_type' => 'term', and
  • In the last parameter, you need to pass the term ID

Other parameters are the same as for post. Please see this documentation for details.

Manually retrieve value

Term meta value is saved in a similar way as post meta. To get term meta value, use the function:

$meta = get_term_meta( $term_id, $field_id, true );
echo $meta;

// Or use this code if field has multiple value
$meta = get_term_meta( $term_id, $field_id, false );
if ( $meta ) {
    foreach ( $meta as $value ) {
        echo $value;
    }
}

Important Note:

The helper function returns only raw data of term meta value. It doesn’t return meaningful information for images, file, etc. To do that, please add a small piece of code as follow:

// Getting images
$image_ids = get_term_meta( $term_id, $field_id, false ); // Media fields are always multiple.
foreach ( $image_ids as $image_id ) {
    $image = RWMB_Image_Field::file_info( $image_id, array( 'size' => 'thumbnail' ) );
    echo '<img src="' . $image['url'] . '" width="' . $image['width'] . '" height="' . $image['height'] . '">';
}

These are some helper function that you can use to retrieve more info:

Field typeHelper function(s)
image, image_advanced, plupload_image, thickbox_imagewp_get_attachment_image_src()
wp_get_attachment_image_url()
RWMB_Image_Field::file_info( $image_id, $args ); (where $args is an array and accepts only size attribute)
file, file_advancedget_attached_file()
RWMB_File_Field::file_info( $image_id );
oembedRWMB_OEmbed_Field::get_embed( $url );
taxonomy, taxonomy_advancedget_term()
userget_userdata()
postget_post()

To understand which “raw” value is saved for subfields, please read this documentation.

MB Settings Page

Installation

Before installing the extension, you need to install Meta Box plugin first.

  1. Go to Plugins → Add New and search for Meta Box
  2. Click Install Now button to install the plugin
  3. After installing, click Activate Plugin to activate the plugin

The extension is just a WordPress plugin, you can install it like a normal WordPress plugin.

  1. Go to Plugins, click Add new, then click Upload plugin.
  2. Choose the .zip file you downloaded and click Install now
  3. After finishing upload, click Activate to finish.

After installing, you need to register a settings page and register meta boxes (and fields) for that settings page.

Register settings page

Registering a settings page is done by filter mb_settings_pages. The code to add a settings page looks like this (this registers a theme options page under Appearance menu):

https://gist.github.com/rilwis/c86edf2fae070f2ab588#file-register-settings-page-php

The filter takes an array of defined settings pages as the argument. The callback function must return an array of settings pages.

Each settings page is defined by an array of the following options:

NameDescription
idPage ID. Required. Will be used as the slug in URL and option name (if option_name missed).
option_nameOption name where settings data is saved to. Optional. Takes id if missed. If you want to use theme mods, then set this to theme_mods_$themeslug.
menu_titleMenu title. Optional. Takes page_title if missed.
page_titlePage title. Optional. Takes menu_title if missed. Note: either menu_title or page_title (or both) must have value.
capabilityRequired capability to access the settings page. Optional. Default edit_theme_options.
icon_urlThe icon for the menu. To use a Dashicon, set this to dashicon-icon-name. To use a SVG data image as a CSS background, set this to data:image/svg+xml;base64.... To use an image, set this to image URL. See icon_url parameter of add_menu_page() function.
positionMenu position. See position parameter of add_menu_page() function.
parentID of the parent page. Optional. Can be WordPress menu or custom settings page menu. See examples below for more details.
submenu_titleSet this to the default submenu title (first submenu) if the settings page is a top-level menu. Optional.
help_tabsList of help tabs. Array in format 'tab-id' => 'Tab Content'. Optional.
styleHow do you want to style the settings page. Supports boxes which has same the style as normal WordPress meta boxes (like in the edit post screen) and no-boxes which has the same style as WordPress settings page. In no-boxes style, each meta box is a section of the settings page.
columnsThe number of columns in the meta boxes. Can be 1 or 2. You might want to use 1 column with no-boxes style to match WordPress style.
tabsOrganized meta boxes and fields in tabs (see the example below). This param takes an array of (tab_id => Tab Title). Note: when using this param, you must specify which tab the meta box belongs by adding a new parameter 'tab' => tab_id. See example below.
submit_buttonThe custom text for submit button. Optional.
messageThe custom message displayed when saving options. Optional.

Examples

This example registers a top-level menu pages and 2 sub settings page:

https://gist.github.com/rilwis/c86edf2fae070f2ab588#file-register-multi-pages-php

Here is the result:

Register settings pages
Register settings pages

Note that:

  • The submenu_title allows us to set the first submenu of the menu to Settings (while the top-level menu is Options).
  • The parent of submenus are set to the ID of top-level menu (my-options).

In case you want to add submenu to existing WordPress pages, set the parent option to:

ValuePage
index.phpDashboard
edit.phpPosts
upload.phpMedia
link-manager.phpLinks
edit.php?post_type=pagePages
edit-comments.phpComments
edit.php?post_type=your_post_typeCustom post type
themes.phpApperance
plugins.phpPlugins
users.phpUses
tools.phpTools
options-general.phpSettings

Register settings meta boxes and fields

Registering settings meta boxes and fields for settings pages is the same as for posts. You need to hook to rwmb_meta_boxes and set a param settings_pages to the settings page(s) you want to add to.

The sample code is below:

https://gist.github.com/rilwis/c86edf2fae070f2ab588#file-register-settings-fields-php

Note:

  • You must set settings_pages to the ID of the settings page. If you want to add meta boxes to 2 or more settings pages, set it to an array of settings pages’ IDs
  • All options for fields stay unchanged.
  • The settings page uses 2 columns layout, which mimic WordPress post screen and the value for context has the same meaning.

Using tabs

The example below registers 1 top level settings page with 3 tabs. Each tabs has one meta box. The style is set to no-boxes and columns is set to 1 to match WordPress style:

https://gist.github.com/rilwis/c86edf2fae070f2ab588#file-tabs-style-php

Here is the result:

Settings Page - Tab Style
Settings Page – Tab Style

Getting settings value

Using helper function

Since version 1.2, you’re able to use helper function rwmb_meta to get settings value.

$value = rwmb_meta( $field_id, array( 'object_type' => 'setting' ), $option_name );
echo $value;

The code is very similar to get post meta. The differences are:

  • In the 2nd parameter, you need to pass 'object_type' => 'setting', and
  • In the last parameter, you need to pass the option name for the settings page

Other parameters are the same as for post. Please see this documentation for details.

Manually retrieve value

Settings values are saved in WordPress option as an array with the option name is option_name set when defining the settings page. The keys of that array are the fields IDs and values are the saved values.

To get the settings value, use the following code:

$settings = get_option( 'option_name' );
$field_id = 'your_field_id';
if ( isset( $settings[$field_id] ) ) {
    return $settings[$field_id];
}

Important Note:

The code returns only raw data of term meta value. It doesn’t return meaningful information for images, file, etc. To do that, please add a small piece of code as follow:

// Getting images
$image_ids = get_term_meta( $term_id, $field_id, false ); // Media fields are always multiple.
foreach ( $image_ids as $image_id ) {
    $image = RWMB_Image_Field::file_info( $image_id, array( 'size' => 'thumbnail' ) );
    echo '<img src="' . $image['url'] . '" width="' . $image['width'] . '" height="' . $image['height'] . '">';
}

These are some helper function that you can use to retrieve more info:

Field typeHelper function(s)
image, image_advanced, plupload_image, thickbox_imagewp_get_attachment_image_src()
wp_get_attachment_image_url()
RWMB_Image_Field::file_info( $image_id, $args ); (where $args is an array and accepts only size attribute)
file, file_advancedget_attached_file()
RWMB_File_Field::file_info( $image_id );
oembedRWMB_OEmbed_Field::get_embed( $url );
taxonomy, taxonomy_advancedget_term()
userget_userdata()
postget_post()

To understand which “raw” value is saved for subfields, please read this documentation.