Skip to content

Custom Metabox

1. Using Option Builder

A powerful Option Builder allows easy creation of Metaboxes.

Example: Creating portfolio-option metabox for portfolio post type.
php
$prefix = 'cmf_metabox';

Metabox::create(
	$prefix . '_portfolio_options',
	array(
		'title'     => esc_html__( 'Portfolio Options', 'textdomain' ),
		'post_type' => 'portfolio',
	)
);

Section::create(
	$prefix . '_portfolio_options',
	array(
		'title'  => esc_html__( 'Portfolio Info', 'textdomain' ),
		'fields' => array(
			array(
				'id'    => 'portfolio_title',
				'type'  => 'text',
				'title' => esc_html__( 'Portfolio Title', 'textdomain' ),
			),
			array(
				'id'    => 'portfolio_thumbnail',
				'type'  => 'media',
				'title' => esc_html__( 'Portfolio Thumbnail', 'textdomain' ),
			),
		),
	)
);
Arguments
NameTypeDefaultDescription
titlestring-The label that appears above the field.
post_typearray|stringpostSpecify one or more post types where the metabox should appear.
fieldsarray-Specify one or more fields for the metabox.
idstring-Identifier for the field.
typestringtextField type.

2. Creating Manually

Steps:
  1. Navigate to:
    sh
    {project_root}/wp-content/plugins/codexshaper-framework/src/Metaboxes
  2. Create a file using UpperCamelCase.php naming convention (e.g., TestMetabox.php).
  3. Open the file in a text editor and insert the following code:
php
<?php

namespace CodexShaper\Framework\MetaBoxes;
use CodexShaper\Framework\Foundation\MetaBox;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class TestMetabox extends MetaBox
{
	public function __construct() {
		// Do your settings here

		parent::__construct();
	}

	public function get_id() {
        return 'cmf_test_metabox';
    }

	public function get_title() {
        return 'Test Metabox';
    }

	public function get_screen() {
        return array( 'post' );
    }

	public function register_sections() {
		$this->add_section([
			'title' => esc_html__('Test Metabox Section', 'textdomain'),
			'fields' => array(
				array(
					'id'    => 'test_metabox_title',
					'type'  => 'text',
					'title' => esc_html__( 'Test Metabox Title', 'textdomain' ),
				),
				array(
					'id'    => 'test_metabox_icon',
					'type'  => 'media',
					'title' => esc_html__( 'Test Metabox Icon', 'textdomain' ),
				),
			),
		]);
	}
}

You should see your new Test Metabox with the Sections and Fields you created.

Custom Metabox Example