Code Snippet to Add Custom Fields to WordPress Posts

Finn J Jan 8, 2025 Custom Fields
How can I add extra information to my blog posts, like a subtitle or a custom image?
What is the process for using `add_meta_box` to create custom fields in the WordPress post editor, and how can I save and retrieve this data efficiently?
Andy answered Jan 8, 2025

Adding Custom Fields to WordPress Posts

Custom Code Solution

This solution adds a subtitle and custom image field to your posts. Place this code in your theme's functions.php file or in a site-specific plugin.

First, register the meta box to appear in the post editor:

add_action('add_meta_boxes', 'register_post_custom_fields');

function register_post_custom_fields() {
    add_meta_box(
        'post_custom_fields',
        'Additional Post Details',
        'render_post_custom_fields',
        'post',
        'normal',
        'high'
    );
}

Create the meta box HTML form:

function render_post_custom_fields($post) {
    wp_nonce_field('post_custom_fields', 'post_custom_fields_nonce');
    
    $subtitle = get_post_meta($post->ID, '_post_subtitle', true);
    $custom_image = get_post_meta($post->ID, '_post_custom_image', true);
    ?>
    <p>
        <label for="post_subtitle">Subtitle:</label><br>
        <input type="text" id="post_subtitle" name="post_subtitle" value="<?php echo esc_attr($subtitle); ?>" style="width: 100%">
    </p>
    <p>
        <label for="post_custom_image">Custom Image URL:</label><br>
        <input type="text" id="post_custom_image" name="post_custom_image" value="<?php echo esc_url($custom_image); ?>" style="width: 100%">
        <button type="button" class="button" id="upload_image_button">Upload Image</button>
    </p>
    <script>
    jQuery(document).ready(function($) {
        $('#upload_image_button').click(function() {
            var image = wp.media({
                title: 'Select or Upload Image',
                button: {
                    text: 'Use this image'
                },
                multiple: false
            }).open().on('select', function() {
                var uploaded_image = image.state().get('selection').first();
                $('#post_custom_image').val(uploaded_image.get('url'));
            });
        });
    });
    </script>
    <?php
}

Save the custom field data:

add_action('save_post', 'save_post_custom_fields');

function save_post_custom_fields($post_id) {
    if (!isset($_POST['post_custom_fields_nonce']) || 
        !wp_verify_nonce($_POST['post_custom_fields_nonce'], 'post_custom_fields')) {
        return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    if (isset($_POST['post_subtitle'])) {
        update_post_meta($post_id, '_post_subtitle', sanitize_text_field($_POST['post_subtitle']));
    }

    if (isset($_POST['post_custom_image'])) {
        update_post_meta($post_id, '_post_custom_image', esc_url_raw($_POST['post_custom_image']));
    }
}

Retrieve and display the custom fields in your theme:

function get_post_subtitle($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    return get_post_meta($post_id, '_post_subtitle', true);
}

function get_post_custom_image($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    return get_post_meta($post_id, '_post_custom_image', true);
}

Usage example in your template files:

$subtitle = get_post_subtitle();
$custom_image = get_post_custom_image();

if ($subtitle) {
    echo '<h2>' . esc_html($subtitle) . '</h2>';
}

if ($custom_image) {
    echo '<img src="' . esc_url($custom_image) . '" alt="">';
}

Plugin Alternative

If you prefer using a plugin, here are reliable options:

  1. Advanced Custom Fields - Popular and feature-rich
  2. Custom Field Suite - Lightweight alternative
  3. Meta Box - Developer-friendly with extensive features

These plugins provide user-friendly interfaces for creating and managing custom fields without coding.