Your First Custom Field — Tutorials — Pure Metafields

Docs/Tutorials/Your First Custom Field

Your First Custom Field

A hero section for Pages: a title, a background image, and an on/off switch — registered in code, saved, and displayed.

  1. Register the metabox

    Add this to your theme's functions.php:

    PHP
    add_filter( 'tp_meta_boxes', function( $boxes ) {
        $boxes[] = [
            'metabox_id' => 'page_hero',
            'title'      => 'Page Hero',
            'post_type'  => [ 'page' ],
            'fields'     => [
                [ 'id' => 'hero_title',   'type' => 'text',   'label' => 'Title' ],
                [ 'id' => 'hero_image',   'type' => 'image',  'label' => 'Background' ],
                [ 'id' => 'hero_enabled', 'type' => 'switch', 'label' => 'Show hero?',
                  'data_type' => 'boolean' ],
            ],
        ];
        return $boxes;
    } );
  2. Fill it in

    Open any Page to edit it. A Page Hero box appears under the content editor. Type a title, pick a background image, switch it on, and click Update.

  3. Display it on the front end

    In page.php (or wherever your Page template lives):

    PHP · page.php
    if ( tpmeta_field( 'hero_enabled' ) ) {
        $title = tpmeta_field( 'hero_title' );
        $img   = tpmeta_image_field( 'hero_image' );
        ?>
        <section class="hero" style="background-image:url(<?php echo esc_url( $img['url'] ?? '' ); ?>)">
            <h1><?php echo esc_html( $title ); ?></h1>
        </section>
        <?php
    }
  4. Check it in the browser

    View the page. If the hero doesn't show, confirm the switch is really on — see Best Practices → boolean switches — and that hero_enabled matches the field's id exactly.

Where to next

Add a repeater for a list of stats or logos under the hero — see Creating Field Groups. Or build the same thing with no code at all — see Meta Builder.