Using WordPress ‘post_custom_meta_box()’ PHP function

The post_custom_meta_box() WordPress PHP function displays custom fields form fields.

Usage

post_custom_meta_box( $post );

Custom Example

$post = get_post(42);
post_custom_meta_box( $post );

Parameters

  • $post (WP_Post) – Required. The current post object.

More information

See WordPress Developer Resources: post_custom_meta_box

Examples

Display Custom Fields for a Specific Post

This example retrieves a specific post and displays its custom fields using the post_custom_meta_box() function.

// Get a specific post by ID
$post = get_post(42);

// Display custom fields for the post
post_custom_meta_box( $post );

Display Custom Fields for the Current Post in the Loop

This example displays custom fields for the current post within the WordPress loop.

// Start the WordPress loop
while ( have_posts() ) {
the_post();

// Display custom fields for the current post
post_custom_meta_box( $post );
}

Display Custom Fields for a Post by Slug

This example retrieves a post by its slug and displays its custom fields using the post_custom_meta_box() function.

// Get a post by its slug
$post = get_page_by_path('my-post-slug', OBJECT, 'post');

// Display custom fields for the post
post_custom_meta_box( $post );

Display Custom Fields for a Custom Post Type

This example displays custom fields for a specific custom post type.

// Get a custom post type by ID
$post = get_post(42, OBJECT, 'my_custom_post_type');

// Display custom fields for the custom post type
post_custom_meta_box( $post );

Display Custom Fields for a Post in a Custom Meta Box

This example creates a custom meta box for the post edit screen and displays custom fields using the post_custom_meta_box() function.

// Add a custom meta box to the post edit screen
add_action('add_meta_boxes', 'my_custom_meta_box');

function my_custom_meta_box() {
add_meta_box('my_meta_box', 'My Custom Meta Box', 'display_my_custom_meta_box', 'post', 'normal', 'high');
}

// Display custom fields in the custom meta box
function display_my_custom_meta_box( $post ) {
post_custom_meta_box( $post );
}