Skip to main content

Custom Meta

Declare custom meta in inc/fx-meta.php or with the associated custom post type in inc/fx-cpt.php.

To setup a new custom meta section, create a new instance of CustomPostMeta and send through an array of inputs.

$custom_meta = CustomPostMeta($id: string, $options: array, $meta_boxes: array, $post_type: string);

The Class is a wrapper around the Wordpress add_meta_box method, but handles the meta box rendering and saving.

Example

$pages = new CustomPostMeta('page-meta', [
'title' => 'Page Meta',
'position' => 'normal',
'priority' => 'high',
'prerequisite' => !is_home_page(),
], [
'subheading' => [
'type' => 'textfield',
'title' => 'Subheading'
]
], 'page');

Options

The options array have the following shape:

$options = [
title: string,
position: 'normal' | 'side' | 'advanced',
priority: 'high' | 'low' | 'default',
prerequisite: bool,
grouped: ?bool,
];

Prerequisite

Use this option to conditionally show meta boxes.

A common case is checking the page template:

function is_home_page() {
// Get the current post
$post = get_current_post();

return 'page-home.php' === get_post_meta($post->ID, '_wp_page_template', true);
}

N.B. this option also accepts an array of IDs (you can exploit this to select the "Posts" page)

Grouped

When grouped, meta data will be combined and saved as one entry under the section $id.

This is useful when you will need a collection of data at one time, as it will store all of the data in one field.

// inc/fx-meta.php
$home_hero_meta = new CustomPostMeta('home-hero', [
'title' => 'Hero Meta',
'position' => 'normal',
'priority' => 'high',
'prerequisite' => is_home_page(),
], [
'hero_title' => [
'type' => 'textfield',
'title' => 'Title'
],
'hero_subtitle' => [
'type' => 'textfield',
'title' => 'Subtitle'
],
], 'page');

// page-home.php
$hero_meta = json_decode(fx_get_meta('home-hero'), true);
$hero_title = $hero_meta['hero_title'];
$hero_subtitle = $hero_meta['hero_subtitle'];

Note: Using the section meta type with a limit of 1 is a simple alternative.

Usage with CPT

File: inc/fx-cpt.php

To add custom meta to a custom post type, use the add_meta_section method available on the CPT class. So after initiating you can easily add new meta sections.

// Create the class
$custom_post_type = new CPT();
// Add a new section for custom meta
$custom_post_type->add_meta_section($id: string, $options: array, $meta_boxes: array);