WordCamp Asia 2025
Meta Box

Guide

Looking for a solution for your problem? Here are guides on using Meta Box and WordPress plugins/code to solve them.

Get Posts by Custom Fields in WordPress - Part 2

Get Posts by Custom Fields in WordPress - Part 2

In part 1 of this series, we learned about how to get posts by custom fields in WordPress with the WP_Query function. However, if we need to deal with databases, it’s better to find another faster, easier, and more convenient way. That method is joining wp_posts and wp_postmeta tables together, and then querying by SQL. In part 2 of the series “How to get posts by custom fields in WordPress”, we’ll use this way to add the advanced searching feature that allows users to search by keywords in posts / pages titles and custom fields content.

Continue reading "Get Posts by Custom Fields in WordPress - Part 2"

PHP Techniques to Write Clean and Readable Code

PHP Techniques to Write Clean and Readable Code

When starting a project, developers should think about how to write clean and readable PHP code so that it can be easy to maintain and fix when there’s a bug. To meet these requirements, developers in the team should follow coding standards and best practices.

What are these coding standards and best practices? Are there any PHP techniques to write clean and readable code? The answers can be found right in this article!

PHP clean code techniques

Why do you need PHP clean code?

For simple reasons:

  • You spend much more time to read code than to write code. With clean code, you're easy to read and understand what you write. Especially, after months or years revisiting the code, you'll still understand it. Or if someone else reads your code, they'll easy to understand.
  • Clean code expresses the business logic better than bad code. You'll be lost in a maze of if...else with about 5-10 nested conditions, and you have no idea what's going on!
  • Clean code gives you an oppoturnity to document the process, the "how" to write PHP code and the best practices. This documentation is valuable accross the company/team and can be used to train other members.
  • If you work with WordPress or any open source project, collaboration and contribution is key. With PHP clean code, you say the same language with other developers around the world and increase the chance for you or them to contribute to shared projects.

In our company, as we create multiple plugins for WordPress (Meta Box and Slim SEO), a developer might work on a different project at one time. And they usually collaborate with other people to develop new features or fix bugs. So, writing PHP clean code is a must for us to keep the products easy to maintain and develop.

Coding Standards

Coding standards are the rules for coding that are set up by developers in a project. When every project member follows these coding standards, the code can be easy to read, reuse, and improve.

These are the benefits of the coding standards:

  • The coding standards play an important role as the blueprint for all the project members. That helps everyone to understand each other’s code more easily.
  • With the appropriate way of coding, your code will become simpler and cleaner, helping you avoid common mistakes.
  • When you want to copy the code to use for other projects, you can easily do so without reducing the code quality.

The coding standards consist of these following common elements:

  • Naming variables, constants, functions, classes, …
  • Using spaces or tabs
  • Declaring and using variables
  • Comment
  • The maximum length for a line of code, file, ...

In case you’re developing products for WordPress like themes and plugins, you have to follow the WordPress coding standards. However, these coding standards have some strict rules that I think you may not need to follow. And here are the main rules in the WordPress coding standards that you should comply with:

Indentation and Line Length of Code

You should use tabs instead of spaces to help computers display the code in the most flexible way. In terms of line length, a line of code should be in 75 - 85 characters to make the code more readable.

Declare Arrays

WordPress requires developers to declare long array syntax (1, 2, 3). However, from the 5.4 version, PHP supports writing short array syntax [1, 2, 3]. And it’s totally fine to use short array syntax. In fact, it’s encouraged to do so.

Shorthand PHP Tag

WordPress requires you to write the full PHP tag as follows:

<?php echo 'Some text'; ?>

But from the 5.4 version, PHP supports writing short tags (this feature is always on), so you can use it for a cleaner command:

<?= 'Some text'; ?>

Control Structure

Control structure includes if, for, while, switch, … Between these words and the opening bracket, you should use ONE space (press the spacebar only ONCE) to distinguish them from function calls.

if ( ( condition 1 ) || ( condition 2 ) ) { 
    the action to be implemented 1; 
} elseif ( ( condition 3 ) && ( condition 4 ) ) { 
    the action to be implemented 2; 
} else { 
    the action to be implemented by default; 
}

As for switch commands, you can code as follows:

switch ( condition ) {
    case 1:
        the action to be implemented
        break;

    case 2:
        the action to be implemented
        break;
    default:
        the default action
        break;
}

Function Calls

When calling a function, you should add ONE space between the function name, the opening parenthesis, and the first variable, don’t write it without spaces. You should also add a space between the comma and each parameter, between the last parameter, the closing bracket, and the semicolon. For better visualization, see the below example of a function call coding standards:

$var = foo( $bar, $baz, $quux );

Naming Files and Classes

In WordPress, all classes must be named Class_Name. You need to capitalize the first letter of each word and separate it with an underscore.

The filename of the class is written as class-class-name.php. You have to add the class- prefix, lowercase class names, and separate words with dashes.

However, when working with “big” plugins and themes, you should use Composer to autoload files. In this case, the coding standards above can’t work anymore because Composer follows PSR’s rules. Therefore, it’s crucial to follow the PSR files and classes naming rules if you use Composer:

  • Class name: in the form of ClassName (capitalize the first letter of each word and write the words without spaces).
  • Filename: in the form of ClassName.php (the file’s name is the same as the class’s name).

In addition, these files are placed in the folders that correspond to their namespaces. For example, a class with the full name of \ALSearch\Shortcode\Field will be placed in the src\ShortCode folder, and its file’s name is Field.php. In this example, the src folder corresponds to the ALSearch namespace, while other parts of the class name correspond to the parts that are in the same hierarchy.

The ?: Operator

WordPress doesn’t allow using the ?: operator in the short form. It always requires writing in the long form:

$type = $type ? $type : 'select';

However, from PHP version 5.3, you can write it shorter to make them easier to read as follows:

$type = $type ?: 'select';

PHP Best Practices

There are several coding techniques that we use in our projects to make the code more optimal and easier to read and fix. I have summarized those techniques in the following sections:

Consistency

You should code in the same style for a function, class, or file, and avoid coding in different styles for the same code like the following example:

<?php if ( $args['label'] ) : ?>
    <span class="als-field__label"><?php echo esc_html( $args['label'] ); ?></span>
<?php endif; ?>

<?php
if ( $args['prefix'] ) {
    echo '<span class="als-field__prefix">' . esc_html( $args['prefix'] ) . '</span>';
}

The above code displays the label and the prefix. Although the coding styles are different, they return the same result. Therefore, we should rewrite them consistently as follows:

if ( $args['label'] ) {
    echo '<span class="als-field__label">', esc_html( $args['label'] ), '</span>';
}
if ( $args['prefix'] ) {
    echo '<span class="als-field__prefix">', esc_html( $args['prefix'] ), '</span>';
}

Early Return

If the conditional blocks are too large, the code will be very difficult to read and you will find it harder to follow the logic. To fix this, you need to write small conditional blocks. One of the techniques to do it is "early return" - return as soon as possible.

For instance, I have the following code that hasn’t been optimized:

if ( 'none' !== $field['sanitize_callback'] ) {
    if ( is_callable( $field['sanitize_callback'] ) {
        $value = call_user_func( $field['sanitize_callback'], $value, $args );
    } else {
        // a very long code
    }
}
return $value;

When you apply the “early return” technique, this code is rewritten as follows:

if ( 'none' === $field['sanitize_callback'] ) {
    return $value;
}
if ( is_callable( $field['sanitize_callback'] ) {
    return call_user_func( $field['sanitize_callback'], $value, $args );
}
// a very long code.
return $value;

Set the Default Value

Setting the default value helps us remove conditional statements that check the existence of that value, thus making your code simpler and more readable.

Below is the code that hasn’t been optimized:

if ( isset( $args['prefix'] ) && $args['prefix'] !== '' ) {
    echo esc_html( $args['prefix'] );
}
if ( isset( $args['label'] ) && $args['label'] !== '' ) {
    echo esc_html( $args['label'] );
}

After setting the default value, the code becomes more readable:

$args = wp_parse_args( $args, [
    'prefix' => '',
    'label' => '',
] );
 
if ( $args['prefix'] ) {
    echo esc_html( $args['prefix'] );
}
if ( $args['label'] ) {
    echo esc_html( $args['label'] );
}

Or even better

echo esc_html( $args['prefix'] ) ?? '';
echo esc_html( $args['label'] ) ?? '';

Output Multiple Values with echo

When we need to output a lot of texts, we usually code like this:

echo '<span class="als-field__prefix">' . esc_html( $args['prefix'] ) . '</span>';

However, this approach isn’t as optimal as using the echo function. The echo function allows us to pass many parameters at once, so it works faster than the normal function:

echo '<span class="als-field__prefix">', esc_html( $args['prefix'] ), '</span>';

Use Lazy Declaration and Declare Only When Necessary

Remember that you should only declare variables when needed. This declaration also includes creating the initial value.

In addition, you should declare as late as possible. Better yet, you should declare right on the code that uses that variable.

Below is an example of the unnecessary variable declaration:

$date = parent::get_date();
$format = ''; // Declare unnecessarily because this variable is declared again in the below code

if ( $meta ) {
    $format = 'Y-m-d';
    return date( $format, $date );
}

You should declare the variable as follows:

$date = parent::get_date();

if ( $meta ) {
    $format = 'Y-m-d';
    return date( $format, $date );
}

Here is an example of declaring variables too early when we haven’t used them yet:

$format = 'Y-m-d';

// A very long code.

return date( $format, $date );

You should only declare the $format variable right before the code that uses it as follows:

// A very long code.

$format = 'Y-m-d';
return date( $format, $date );

Last Words

Improving and optimizing code is always a matter of concern for coders. The cleaner and more readable your code is, the more efficient your teamwork is. Besides, it will be easier to handle when there’s an issue. Therefore, don’t forget to apply the above techniques to get the best results.

At Meta Box, we're trying our best to write the best code for our WordPress plugins. They are plugins for developers, so the coding quality is our top priority.

If there are any other useful tips for coding, feel free to share it with us in the comment section!

Create and Import a Project Portfolio Using Elementor, Meta Box and WP All Import

Create and Import a Project Portfolio with Elementor, Meta Box and WP All Import

You need to create a website for a client - and the client has a whole bunch of projects that they want to show on their website. Not only that but there are over 30 projects - and each project portfolio has over 40 images and its own page. Sounds like a lot of work right? Luckily, using WordPress along with WP All Import Pro and Meta Box, this is a piece of cake. In this tutorial, I will walk you through how to do this.

Continue reading "Create and Import a Project Portfolio with Elementor, Meta Box and WP All Import"

Create an OTA Website Like Booking.com with Meta Box Plugin - P3: Create Filters for Single Hotel Pages

Create an OTA Website Like Booking.com with Meta Box Plugin - P3: Create Filters for Single Hotel Pages

In part 2 of the series “Create an OTA website like booking.com with Meta Box plugin”, we created filters that allow users to search for hotels on the Hotel archive page. Then, to help users find their desired rooms in each hotel conveniently, we need to filter vacancies in Hotel single pages.

Continue reading "Create an OTA Website Like Booking.com with Meta Box Plugin - P3: Create Filters for Single Hotel Pages"

Create an OTA Website Like Booking.com with Meta Box Plugin P2 Create Filters on the Archive Page

Create an OTA Website Like Booking.com with Meta Box Plugin - P2: Create Filters on the Archive Page

In part 1 of the series “Create an OTA Website Like Booking.com with Meta Box plugin”, we completed creating a page to introduce hotel rooms and creating custom fields to fill in the booking data. But an OTA website needs more than that: a filter hotel system to help users search for hotels that fit their requirements easily and quickly. So, this next part is about how to create filters on the Hotel archive page. Let’s find out!

Continue reading "Create an OTA Website Like Booking.com with Meta Box Plugin - P2: Create Filters on the Archive Page"

Create an OTA Website Like Booking.com with Meta Box Plugin P1 Create a Page to Introduce Hotel Rooms

Create an OTA Website Like Booking.com with Meta Box Plugin - P1: Create a Page to Introduce Hotel Rooms

Nowadays, having an OTA (Online Travel Agent) website is very popular with companies and agencies, especially ones that supply the hotel booking service. Some of the most popular websites in this field are agoda.com and booking.com with professional hotel booking systems. If you want to build an OTA website just like them, follow our series “Create an OTA Website Like booking.com and agoda.com”.

In the first article of this series, we’ll create a single page for each hotel and create custom fields to enter the hotel information, and then display them on the website.

Continue reading "Create an OTA Website Like Booking.com with Meta Box Plugin - P1: Create a Page to Introduce Hotel Rooms"

Create a Custom Menu for Restaurants - P2 - Use Gutenberg

Create a Custom Menu for Restaurants - P2 - Use Gutenberg

In the previous post, we have created a custom menu that allows restaurant owners to easily change the menu dishes. However, this is the way for websites that use the Elementor page builder only. In case you don’t want to spend money to buy this plugin, you can use Gutenberg instead. It's free, but you need to use a few lines of code. Let’s read detailed instructions in this article.

Continue reading "Create a Custom Menu for Restaurants - P2 - Use Gutenberg"

How to Show Reviews on SERPs using Schema

How to Show Reviews on SERPs using Schema

Have you ever searched for a product and found a five-star-rating below the product on the Search Engine Results Pages (SERPs)? Such star-ratings not only impress users but also create authenticity for the products. If you want to display your site’s ratings on the SERPs too, keep reading this article to learn about the fastest and most accurate way to show this by using Schema plugins.

Continue reading "How to Show Reviews on SERPs using Schema"