When responding to people’s questions about Meta Box and custom fields, I found a lot of senior developers have been integrated Meta Box into their websites deeply. They’ve made the code for meta box registration easier to understand, and organized it very well. In this article, I would like to give some suggestions on how to optimize the code to make meta boxes and custom fields declaration more streamlined and simpler.

Why Simplify The Code?

There are many reasons, but I think the following reasons are quite important:

  • Your code will become shorter, e.g. you’ll write less code, and thus - faster.
  • You or someone else will read your code faster and easier to understand. If you need someone to review or code together, the shorter code will help them understand what you want the quickest.
  • You can organize your code more structured and logical (see below for details).

Simplifying code is a good practice in programming languages ​​such as JavaScript (arrow function) or PHP (short array syntax). Let’s take a look at the tips to help you simplify the code below.

Use Anonymous Function

Instead of writing:

add_filter( 'rwmb_meta_boxes', 'prefix_your_function' );
function prefix_your_function( $meta_boxes ) {
    $meta_boxes[] = ...
    return $meta_boxes;
}

Let’s write:

add_filter( 'rwmb_meta_boxes', function ( $meta_boxes ) {
    $meta_boxes[] = ...
    return $meta_boxes;
}

You don’t have to write the name of the function (sometimes finding a good function name is a headache). Note that the anonymous function is only supported in PHP 5.3+.

Use Short Array Syntax

Instead of writing array(), write []. Very simple. These help make your array look nice and compact. Consider the following example:

add_filter( 'rwmb_meta_boxes', function ( $meta_boxes ) {
    $meta_boxes[] = array(
        'title' => 'My Meta Box',
        'fields' => array(
            array(
                'id' => 'name',
                'title' => 'Name',
                'type' => 'text',
            ),
        ),
    );
    return $meta_boxes;
}

You can write:

add_filter( 'rwmb_meta_boxes', function ( $meta_boxes ) {
    $meta_boxes[] = [
        'title' => 'My Meta Box',
        'fields' => [
            [
                'id' => 'name',
                'title' => 'Name',
                'type' => 'text',
            ],
        ],
    ];
    return $meta_boxes;
}

Although the number of lines does not change, you type less. If you are writing JavaScript, you will find it very easy to understand.

Note: short array syntax is supported in PHP 5.4 or later.

Removes optional parameters when not needed

Parameters for meta boxes such as id, autosave, post_types and priority have default values. If you use the default values, then remove them from your code.

Instead of writing:

add_filter( 'rwmb_meta_boxes', function ( $meta_boxes ) {
    $meta_boxes[] = [
        'id' => 'my-meta-box',
        'title' => 'My Meta Box',
        'priority' => 'high',
        'context' => 'advanced',
        'fields' => ...
    ];
    return $meta_boxes;
}

Just write:

add_filter( 'rwmb_meta_boxes', function ( $meta_boxes ) {
    $meta_boxes[] = [
        'title' => 'My Meta Box',
        'fields' => ...
    ];
    return $meta_boxes;
}

This technique can be also applied to custom fields as well.

See also list of meta box settings and list of custom fields settings. All optional settings can be removed.

Reduce Nesting Levels

When the number of custom fields is large or you have multiple groups, your code might look something like this:

There are too many indentations and it is difficult to know which custom field belongs to a group.

To reduce nested code, we can write:

// Create a meta box.
$meta_box = [
    'title' => 'Books',
    'fields' => [],
];

// Add a custom field.
$meta_box['fields'][] = [
    'id'       => 'publisher',
    'name'     => 'Publisher',
    'type'     => 'taxonomy',
    'taxonomy' => 'publisher',
];

// Add a group.
$group = [
    'name'   => 'Authors',
    'id'     => 'authors',
    'type'   => 'group',
    'clone'  => true,
    'fields' => [],
];
// Add a sub-field to group.
$group['fields'][] = [
    'id'   => 'first_name',
    'name' => 'First Name',
    'type' => 'text',
];
// Add another sub-fields.
$group['fields'][] = [
    'id'   => 'last_name',
    'name' => 'Last Name',
    'type' => 'text',
];

// Add group to meta box.
$meta_box['fields'][] = $group;

As you can see, we have only 1 level of indentation and no nesting.

Organize Meta Box Codes Into Different Files

When the number of custom fields and custom meta boxes grows, the number of lines of code can reach hundreds. Putting all the code into a single file will make it long and hard to maintain.

Instead of putting all the code into a single file, you can separate the meta boxes into the following files:

01-header-settings.php
02-layout-settings.php
03-typography-settings.php

Each file will contain an array to declare the meta box as below:

<?php
// 01-header-settings.php

// Return array of meta box settings.
return [
    'title'  => 'Header Settings',
    'fields' => [
        ...
    ],
];

If you have a lot of custom fields in a meta box, you can reduce nesting levels using the above technique:

<?php
// 01-header-settings.php

$fields = [];

// First field.
$fields[] = [
    ...
];

// Second field.
$fields[] = [
    ...
];

// Return meta box.
return [
    'title'  => 'Header Settings',
    'fields' => $fields,
];

Then you can just include these files for registering meta boxes:

add_filter( 'rwmb_meta_boxes', function( $meta_boxes ) {
    $files = [
        '01-header-settings.php',
        '02-layout-settings.php',
        '03-typography-settings',
    ];
    foreach ( $files as $file ) {
        $meta_boxes[] = include $file;
    }
    return $meta_boxes;
} );

The code include $file includes the code in our settings file and will return the result as meta box settings. These settings are used to create a meta box.

If you name the settings file in the correct order (the trick here is using a numeric prefix 01-, 02- as in the example) and put them in the same directory, you can use the glob() function to get the list of files without having to manually declare the file list.

add_filter( 'rwmb_meta_boxes', function( $meta_boxes ) {
    $files   = glob( '/path/to/settings/*.php' );
    foreach ( $files as $file ) {
        $meta_boxes[] = include $file;
    }
    return $meta_boxes;
} );

By doing this, you can copy the settings files for later uses. Code maintenance is also easier because when you need to change, you only change in a small file.

Here are some basic tips to help you organize and simplify your code to create meta boxes and custom fields. Hopefully, they help you write better code. If you have other good tips, let me know in the comments.

You may also like to know "Optimizing Database for Custom Fields in WordPress".

Leave a Reply

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