Blog / WordPress/ Complete Guide to Adding Custom Meta Boxes in WordPress

Complete Guide to Adding Custom Meta Boxes in WordPress

WordPress 文章添加自定义字段面板(Meta Box)完整教程

Adding custom meta boxes to posts or custom post types is a common requirement in WordPress development. This guide walks through the complete process of creating, saving, and displaying a custom field, using a "Product Price" field as an example.

Core Function: add_meta_box

The add_meta_box function is central to creating a custom meta box. Its basic syntax is:

add_meta_box( $id, $title, $callback, $post_type, $context, $priority, $callback_args );

Parameter Overview

  • $id: A unique identifier for the meta box.
  • $title: The title displayed at the top of the box.
  • $callback: The function that outputs the box's HTML content.
  • $post_type: The post type where the box appears (e.g., 'post', 'page', 'product').
  • $context: Where on the edit screen the box appears ('side', 'normal', 'advanced').
  • $priority: The display priority within its context ('high', 'core', 'default', 'low').

Step 1: Register the Meta Box

Register your meta box using the add_meta_boxes hook. This example adds a "Product Price" box to the sidebar for the 'product' post type.

add_action( 'add_meta_boxes', 'register_product_price_meta_box' );
function register_product_price_meta_box() {
    add_meta_box(
        'product_price_meta_box', // Unique ID
        'Product Price', // Title
        'render_product_price_meta_box', // Callback function
        'product', // Post type
        'side', // Context
        'low' // Priority
    );
}

Step 2: Create the Callback Function (Render the Form)

The callback function outputs the HTML form inside the meta box. It must include a security nonce field and handle any previously saved value.

function render_product_price_meta_box( $post ) {
    // Add security nonce field
    wp_nonce_field( 'save_product_price_meta', 'product_price_meta_nonce' );
    // Retrieve saved value
    $price = get_post_meta( $post->ID, '_product_price', true );
    // Output form field
    echo '';
    echo '';
}

Step 3: Save the Meta Box Data

When a post is saved or updated, validate and store the custom field value. This is the most critical step for security.

add_action( 'save_post', 'save_product_price_meta_box' );
function save_product_price_meta_box( $post_id ) {
    // 1. Check if nonce exists and is valid
    if ( ! isset( $_POST['product_price_meta_nonce'] ) || ! wp_verify_nonce( $_POST['product_price_meta_nonce'], 'save_product_price_meta' ) ) {
        return;
    }
    // 2. Check for autosave (skip processing during autosave)
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    // 3. Check user permissions
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
    // 4. Get, sanitize, and save the field data
    if ( isset( $_POST['product_price'] ) ) {
        $price = sanitize_text_field( $_POST['product_price'] );
        update_post_meta( $post_id, '_product_price', $price );
    }
}

Step 4: Display the Field Value in Theme Templates

After saving, you can retrieve and display the value in your theme template files using get_post_meta.

<?php
$price = get_post_meta( get_the_ID(), '_product_price', true );
if ( ! empty( $price ) ) {
    echo 'Price: ' . esc_html( $price );
}
?>

Extension: Display Custom Field in Admin Post List

You can also add the custom field as a column in the admin post list (e.g., All Posts) for easier management.

// 1. Add custom column
add_filter( 'manage_product_posts_columns', 'add_product_price_admin_column' );
function add_product_price_admin_column( $columns ) {
    $columns['product_price'] = 'Product Price';
    return $columns;
}
// 2. Populate the custom column with data
add_action( 'manage_product_posts_custom_column', 'display_product_price_in_admin_column', 10, 2 );
function display_product_price_in_admin_column( $column, $post_id ) {
    if ( $column === 'product_price' ) {
        $price = get_post_meta( $post_id, '_product_price', true );
        echo ! empty( $price ) ? esc_html( $price ) : '—';
    }
}

Complete Code & Usage Notes

Add all the code snippets above in order to your current theme's functions.php file. Ensure that:

  • The post type 'product' matches your actual post type.
  • The meta key (e.g., '_product_price') is consistent throughout the code.
  • All function names are unique to avoid conflicts with other plugins or themes.

Following these steps allows you to robustly add, save, and display custom meta boxes for any WordPress post or custom post type.

Post a Comment

Your email will not be published. Required fields are marked with *.