Technical support hours: Weekdays 02:00 - 10:00 UTC time zone
envato-seller
0
Cart

No products in the cart.

Close
envato-seller
0
Cart

No products in the cart.

Get an offer

How to create Meta Boxes in WordPress? With PHP code.

By BeycanPress / 5 months time ago / Development

Hello everyone from the BeycanPress team. I am Halil, today I will tell you about some various ways to create Meta Boxes in WordPress.

These are, respectively, WordPress’ standard meta box creation method, Codestart Framework, Meta Box (metabox.io) and of course one of the most popular, Advanced Custom Fields, ACF.

First, let’s look at how to create a standard meta box in WordPress without the need for any extra code, framework or plugin. Since we pay great attention to the use of OOP, we will show you how to build each meta box in a class.

Create meta boxes with standard WordPress codes:

Meta box OOP class skeleton

You can add meta boxes to any post type or multiple post types you want with the most basic framework below.

<?php

declare(strict_types=1);

namespace BeycanPress\CreateMetaBox\MetaBoxes;

// This is our helper method, not focus it
use BeycanPress\CreateMetaBox\PluginHero\Helpers;

class PostStyleMetaBox
{
    /**
     * @var array<string>
     */
    private array $postTypes = ['post', 'page'];

    /**
     * Class construct
     * @return void
     */
    public function __construct()
    {
        // Use one time for OOP
        add_action('add_meta_boxes', [$this, 'add']);

        // save post meta data
        add_action('post_updated', [$this, 'save'], 10, 3);

        // you can use another hooks like save_post, publish_post, etc.
        // See: https://developer.wordpress.org/reference/hooks/
    }

    /**
     * @return void
     */
    public function add(): void
    {
        // Use one time for OOP
        add_meta_box(
            'bp-meta-box-post-style', // id
            __('Post Style'), // title
            [$this, 'content'], // callback (HTML content)
            $this->postTypes, // post type, page, product, etc.
            'advanced', // context 'normal', 'advanced', or 'side'
            'high' // priority 'high', 'core', 'default' or 'low'
        );
    }


    /**
     * @param \WP_Post $post
     * @return void
     */
    public function content(\WP_Post $post): void
    {
        // post meta data
        $postStyle = get_post_meta($post->ID, 'bp_post_style', true);

        /**
         * Our nonce field creator method
         * @see https://developer.wordpress.org/reference/functions/wp_nonce_field/
         */
        Helpers::createNewNonceField();

        // It's our view show method
        Helpers::viewEcho('meta-box/post-style', compact('postStyle'));

        // But this method is accepted string, also you can text html directly here
        // But we not recommend use html code in PHP file
    }

    /**
     * @param integer $postId current post id
     * @param \WP_Post $postAfter post saved after data
     * @param \WP_Post $postBefore post saved before data
     * @return bool
     */
    public function save(int $postId, \WP_Post $postAfter, \WP_Post $postBefore): bool
    {
        // Control some things before save
        if (!$this->controlsBeforeThenSave($postId, $postAfter, $postBefore)) {
            return false;
        }

        // Variables
        $postStyle = isset($_POST['bp_post_style']) ? sanitize_text_field($_POST['bp_post_style']) : null;

        // Save post meta data
        update_post_meta($postId, 'bp_post_style', $postStyle);

        return true;
    }

    /**
     * @param integer $postId current post id
     * @param \WP_Post $postAfter post saved after data
     * @param \WP_Post $postBefore post saved before data
     * @return bool
     */
    private function controlsBeforeThenSave(int $postId, \WP_Post $postAfter, \WP_Post $postBefore): bool
    {
        /**
         * Our nonce field control method
         * @see https://developer.wordpress.org/reference/functions/wp_verify_nonce/
         */
        Helpers::checkNonceField();

        // Permission control
        $postType = get_post_type_object($postAfter->post_type);
        if (!current_user_can($postType->cap->edit_post, $postId)) {
            return false;
        }

        // Post type control
        if (!in_array($postAfter->post_type, $this->postTypes)) {
            return false;
        }

        // Autosave control
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return false;
        }

        return true;
    }
}

What does View (HTML) look like?

The “bp_post_style” value must be the same as the one we use in the save method so that we can get the current value.

<p class="post-attributes-label-wrapper page-template-label-wrapper">
    <label class="post-attributes-label">
        <select name="bp_post_style" id="bp_post_style" class="widefat">
            <option value=""><?php _e('None', 'text-domain') ?></option>
            <option value="red" <?php echo $postStyle == 'red' ? 'selected' : ''; ?>><?php _e('Red', 'text-domain') ?></option>
            <option value="green" <?php echo $postStyle == 'green' ? 'selected' : ''; ?>><?php _e('Green', 'text-domain') ?></option>
        </select>
    </label>
</p>

For the better

We have given you simple examples such as green and red. However, you can make your code higher quality by using the enums that come with PHP 8.

Create meta boxes with Codestar Framework (CSF):

So it’s nice to use CSF, ACF and similar packages. Just making definitions is enough. They manage all the HTML elements and the update process for you in the background. All you have to do is access the meta box data.

Yes, in CSF you only need to make certain definitions.

<?php

declare(strict_types=1);

namespace BeycanPress\CreateMetaBox\MetaBoxes;

use CSF;

class PostStyleMetaBox
{
    /**
     * Constructor
     */
    public function __construct()
    {
        CSF::createMetabox('bp_post_style', array(
            'title'     => __('Post Style', 'text-domain'),
            'post_type' => 'post', // Post type
            'data_type' => 'unserialize', // It allows metadata to be created separately for each key instead of a single key.
        ));

        // Wrapper space
        CSF::createSection('bp_post_style', array(
            'fields' => array(
                array(
                    'id'    => 'postStyleA',
                    'type'  => 'text',
                    'title' => __('Post style a:', 'text-domain')
                ),
                array(
                    'id'    => 'postStyleB',
                    'type'  => 'text',
                    'title' => __('Post style b:', 'text-domain')
                ),
            ),
        ));

        $postId = 5; // just for example
        $postStyleA = get_post_meta($postId, 'postStyleA', true);
        $postStyleB = get_post_meta($postId, 'postStyleB', true);

        // If you not use the 'data_type' parameter, you can use the following code.
        $postStyle = get_post_meta($postId, 'postStyle', true);
    }
}

For more information: https://codestarframework.com/documentation/#/configurations?id=metabox-option-framework

Create meta boxes visually in ACF (No-code):

Unlike the first two examples, in ACF, you can create a meta box visually, not with code. So, if you do not have any coding knowledge, the best option for you will be ACF.

I didn’t go into much detail in ACF. Which I don’t know how to use anyway because I usually do my work with code. But I think you can find everything you need in the ACF documentation.

ACF Docs: https://www.advancedcustomfields.com/resources/

creating-meta-boxes-visually-in-acf-1
Create a meta box field group
creating-meta-boxes-visually-in-acf-2
Enter meta box field informations
creating-meta-boxes-visually-in-acf-3
Select your meta box rules. Like post type

Create meta boxes with Meta Box (metabox.io):

If I remember correctly, I used this when I first started developing WordPress. However, a lot may have changed since then. So I’ll give you an example I took from their documentation page.
You can browse the documentation to get more information about how it is used.
Meta Box Docs: https://docs.metabox.io/

add_filter('rwmb_meta_boxes', function (array $metaBoxes) {
    $metaBoxes[] = [
        'title'      => __('Post Style', 'text-domain'),
        'post_types' => 'bp_post_style',
        'fields'     => [
            [
                'name' => __('Post Style', 'text-domain'),
                'id'   => 'post_style',
                'type' => 'text',
            ],
        ],
    ];

    // Add more field groups if you want
    // $metaBoxes[] = ...

    return $metaBoxes;
});

I hope my article was useful. I may not have been able to give many examples, but I offered you 4 different ways to create meta boxes. You can choose the one that suits you best and learn how it works with the documentation. We actively use normal standard meta boxes and CSF. So if you have questions or need help on these topics, feel free to use the comments.

BONUS:

Creating a WordPress REST API with PHP code

10%

off, especially for you

Sign up to receive your exclusive discount, and keep up to date on our latest products & offers!

We don’t spam! Read our privacy policy for more info.

Leave a Reply

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