Menu

Meta Box for WordPress Posts and WP REST API

June 3, 2017 - WordPress

What are Meta Boxes?

Meta box is part of the entry form on the post/page editing admin page.

In the image below we can see Title, Editor, Format and Publish.
Add new post

A bit lower on the page we can also observe custom fields which are a simple key/value version of the custom meta box. The provide us custom fields, however they are not very friendly as the editor doesn’t know right away which fileds to populate.

Custom fields

Note: Custom fields (metadata) are saved in the wp_postmeta table in the database.
wp_postmeta

Generate your own Meta Boxes

If you don’t like custom fields you can use Custom Meta Boxes. There is a couple of generators available and all let you specify the fields and all other necessary data and generate code for functions.php. You copy and paste it and get new fields in the post, page or custom post. Here is an example:
Custom meta box from Generator
Try Meta Box Generator or Metabox.io

Plugins to the rescue

The best option in my opinion is to use plugins that can add custom meta boxes to an edit screen of any post type. They are especially valuable with Custom Post Types.

ACF

The best plugin for the job (without the doubt) is ACF Plugin. Together with ACF to WP-API Plugin they are powerful combination for WP REST API.

As a result there will be no issues with data input and also output.

Note: ACF Plugin aslo enables you to export Custom Fields to php. Go to Custom Fields > Export > php and include php code in your theme or plugin.

Example: Output ACF field to the template

// wrap the code in function check
if(function_exists('get_field')) {
}
<?php
/* acf custom field: cta */
if(get_field('cta')) {
            echo '<div class="small-12 columns">';
            echo  '<h2>' . get_field('cta') . '</h2>' ;
            echo '</div>';
} 

// acf custom field: contributor
$user = get_field('contributor');
var_dump($user);
?> 

Example: Angular template

<div ng-if="post.acf.name">
            <p>{{post.acf.name}}</p>
            <p>{{post.acf.title}}</p>
            <img ng-src="{{post.acf.image}}" />
</div>
<div ng-if="!post.acf.name">No name</div>