How to Bundle Meta Box into another Plugin to Create Custom Fields
Tags: wordpress
Published: 2020-07-28 02:06:45

If you want to use Meta Box to create custom fields or a settings page without installing it, there is another way that is bundling it into another plugin.

You may wonder why we need to do it. It's because when you create a website for clients, it may be a good idea to hide information such as the used plugins. This time, **bundling Meta Box into another plugin** will be an effective way.

Let's see how to do it.

### Bundle Meta Box into a Plugin

### Step 1: Create a New Plugin

In the `wp-content` folder > **plugin**, create a new folder named `project-demo` with a `project-demo.php` file inside. The php file has the following content:

```
<?php/** * Plugin Name: Project Demo  * Plugin URI: https://metabox.io  * Version: 1.0 * Author: Meta Box * Author URI: https://metabox.io */
```

Go to the plugins listing page in the **Admin Dashboard**, you'll see a new plugin named **Project Demo**. Let's activate it.

### Step 2: Bundle Meta Box into the Created Plugin

We must download the necessary libraries of Meta Box into the plugin that you've created.

In the `project-demo` folder, we create a file named `composer.json` with the following content:

```
{    "repositories":[        {            "type": "composer",            "url": "https://wpackagist.org"        }    ],    "require": {        "wpackagist-plugin/meta-box": "dev-trunk",    },    "extra": {        "installer-paths": {            "vendor/meta-box/meta-box": ["wpackagist-plugin/meta-box"],        }    },    "autoload": {        "files": [            "vendor/meta-box/meta-box/meta-box.php",        ]    }}
```

**Note**: By this code, I just bundle the [Meta Box plugin](https://wordpress.org/plugins/meta-box/) (free version) into the plugin I've created. If you want to add other Meta Box's extensions to create advanced custom fields or settings pages, check out [this file](https://github.com/wpmetabox/library/blob/master/composer/composer.json).

When bundling other extensions, especially the premium ones, you must enter the license key of the product (details in [this file](https://github.com/wpmetabox/library/blob/master/composer/composer.json)).

Back to the above code, there are some points that we should pay attention:

-   `"require"`: this is the declaration of the libraries that you need to download. In this example, I declare the Meta Box library only. You can refer to other code to declare the libraries of the extensions here.
-   `"extra"`: this is declaring a path of where we want to store the libraries.
-   `"autoload"`: require to load the libraries automatically when we activate the plugin.

Next, run the **composer install** command in the `project-demo` folder (make sure that you installed Composer).

![You need install Composer to bundle Meta Box to another plugin](https://cdn-images-1.medium.com/max/600/0*gskEDxqwQY6yJjfv.png)

After that, the `project-demo` folder will include these folders and files as follows:

![The plugin folder that is bunded with Meta Box has the following folders and files](https://cdn-images-1.medium.com/max/600/0*vfm7H5g3udfHeYnE.png)

Finally, you must run the following code in the `project-demo.php` file to download the libraries that you've declared:

```
require 'vendor/autoload.php';
```

![you need to download libraries of Meta Box to bundle it to another plugin](https://cdn-images-1.medium.com/max/600/0*kfxGESBrp8YDVOgp.png)

If you are not familiar with using Composer to install Meta Box, you can learn about it [here](https://docs.metabox.io/composer/).

Now, you've finished bundling Meta Box into another plugin already. So you can try creating custom fields using this new plugin from now on.

### Create Custom Post Types and Custom Fields by New Plugin

I'm going to use the created plugin which includes Meta Box to create a new custom post type named `Project`. Then, I will create a custom field for this post type.

Actually, this process is quite similar to when you install Meta Box directly on the website. The only difference is that if you don't bundle extensions providing UI (such as [Meta Box Builder](https://metabox.io/plugins/meta-box-builder/), [MB Custom Post Type](https://metabox.io/plugins/custom-post-type/), [MB Custom Taxonomy](https://metabox.io/plugins/custom-taxonomy/)) into the plugin as I did, you have to code manually. At the same time, instead of writing code to the `function.php` file, you must do it in the .php file of the created plugin (`project-demo.php`).

Follow the below steps and compare to the article "[How to Create a Product Page using Meta Box Plugin](https://metabox.io/create-product-pages/)", you'll see that.

### Step 1: Create a New Custom Post Type

Add the following code into the `project-demo.php` file:

```
// Create a new post typefunction frefix_register_post_type_project(){    $label = array(        'name'                => 'Projects',        'singular_name' => 'Project',    );
```

```
    $args = array(        'labels'               => $label,        'description'       => 'Post type Project',        'supports'          => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions' ),        'rewrite'           => array(            'slug'           => 'project',            'with_front'  => false,            'feeds'         => true,            pages'         => true,        ),        'public'                          => true,        'show_ui'                      => true,        'menu_position'            => 20,        'capability_type'           => 'page',        'map_meta_cap'          => true,        'has_archive'                => true,        'query_var'                   => 'project',        'show_in_rest'              => true,        'show_in_menu'           => true,        'show_in_nav_menus' => true,    );    register_post_type( 'project', $args );}add_action( 'init', 'frefix_register_post_type_project' );
```

Back to the **Admin Dashboard**, you'll see a new menu named `Projects`. It's the custom post type that you've created.

![It's the custom post type that you've created](https://cdn-images-1.medium.com/max/600/0*V05bUY9BZ6DA9vgd.png)

### Step 2: Create Custom Fields for the New Post Type

To create custom fields, there are 2 options for you: manually code or generate code using [Online Generator](https://metabox.io/online-generator/). Then, copy and paste this code (as the example below) into the `project-demo.php` file:

```
// Add custom fields for the Project post typefunction prefix_add_fields_project( $meta_boxes) {    $meta_boxes[] = [        'title'             => 'Information project',        'post_types' => 'project',        'fields'          => [            [                'id'       => 'investors',                'name' => 'Investors',            ],            [                'id'       => 'customer',                'name' => 'Customer',            ],            [                'id'       => 'description',                'name' => 'Description',                'type'   => 'textarea',            ],            [                'id'       => 'image',                'name' => 'Images',                'type'   => 'image_advanced',            ],        ],    ];    return  $meta_boxes;}add_filter( 'rwmb_meta_boxes', 'prefix_add_fields_project' );
```

Right now, try creating/editing an article in the `Project` post type, the fields will appear as follows:

![The fields will appear as follows](https://cdn-images-1.medium.com/max/600/0*x8hxoOzHH5JSQPZg.png)

### Step 3: Display the Values of the Custom Fields into the Frontend

Create a Template for Single Page of the Project Post Type

Add the following code to the `project-demo.php` file:

```
// Register a new template for the single page of Project post typefunction prefix_project_template( $template ) {    if(  is_singular( 'project' )) {
```

```
        $new_template = plugin_dir_path( __FILE__ ) . 'project-template.php';
```

```
        if ( '' != $new_template ) {            return $new_template ;        }    }    return $template;}add_filter( 'template_include', 'prefix_project_template', 99 );
```

Next, create a new file in the `project-demo` folder that named `project-template.php` (it must have the name as we've declared above) with the following content:

```
<?php get_header(); ?><div class="content">    <h3><a href="<?php  the_permalink() ?> " title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>    <p><span class="uabb-meta-date"> <?php echo get_the_date('d.m.Y'); ?> </p></h5></div><?php get_footer(); ?>
```

#### Display the Values of the Custom Fields into the Created Template

Add the following code to the content of the template file (`project-template.php`):

```
<div class="img-post">        <div>            <?php                 $images = rwmb_meta( 'image', array( 'size' => 'full' ) );                foreach ( $images as $image ) {                    echo '<img src="'. $image['url']. '">';                }            ?>        </div>    </div>    <div class="infomation">        <?php            $investors = rwmb_meta( 'investors', '', get_the_ID() );            $customer = rwmb_meta( 'customer', '', get_the_ID() );            $description = rwmb_meta( 'description', '', get_the_ID() );        ?>        <table>            <tr>                <td class="col-1">Investors</td>                <td><?php echo $investors; ?></td>            </tr>            <tr>                <td class="col-1">Customer</td>                <td><?php echo $customer; ?></td>            </tr>            <tr>                <td class="col-1">Description</td>                <td><?php echo $description; ?></td>            </tr>        </table>    </div>
```

At this time, in the single post page of the `Project` post type, the content will be displayed as follows:

![in the single post page of the Project post type, the content will be displayed as follows](https://cdn-images-1.medium.com/max/600/0*zVTHOUwBKtqvc5K9.png)

Fields and their values are not displayed well, so we need to style them a bit.

#### Use CSS to Style the Fields Display

I create one more file named `style.css` in the `project-demo` folder. Then, I enqueue it into the `project-demo.php` file as following:

```
function prefix_project_styles() {    wp_register_style( 'prefix_main-style', plugin_dir_url( __FILE__ ) . '/style.css', 'all' );    wp_enqueue_style( 'prefix_main-style' );}add_action( 'wp_enqueue_scripts', 'prefix_project_styles' );
```

The structure of the `project-demo` folder is like this:

![The plugin that is bundled with Meta Box will have this structure](https://cdn-images-1.medium.com/max/600/0*vvLQcZHaX12q6ybi.png)

Depending on how you want to display the custom fields, you add the corresponding code to the `style.css` file. For example:

```
.information table, td{    border: 1px solid black;}
```

```
img {    display: inline-block!important;    height: auto;    max-width: 200px!important;    margin-right: 15px!important;    margin-bottom: 20px;}
```

```
.content {    width: 800px;    margin: 0 auto;}
```

```
.col-1 {    width: 30%;}
```

After that, the fields' values will be displayed as follows:

![The fields' values will be displayed as follows](https://cdn-images-1.medium.com/max/600/0*akxCKlvjVtaAAFcc.png)

So you've finished creating a new custom post type and custom fields, then displaying them into the frontend by the new plugin that includes Meta Box.

You can refer to the entire source code which I used in this article here:

<https://github.com/wpmetabox/tutorials/tree/master/plugin-bundle-metabox>

### Last Words

Hopefully, you've had an additional way to use Meta Box for your [WordPress theme](https://gretathemes.com/wordpress-themes/) or on the clients' site that you don't have to install or display the Meta Box menu in the **Admin Dashboard**. If you're wondering anything, leave a comment. Finally, remember to follow our upcoming articles to dig in advanced techniques in development.

--- --- ---

The publication at [Meta Box](https://metabox.io/bundle-metabox-plugin-create-customfields/).