Using WordPress ‘register_and_do_post_meta_boxes()’ PHP function

The register_and_do_post_meta_boxes WordPress PHP function registers the default post meta boxes and runs the do_meta_boxes actions.

Usage

register_and_do_post_meta_boxes( $post );

Custom example:

Input:

$post = get_post( 42 ); // Assuming post with ID 42 exists
register_and_do_post_meta_boxes( $post );

Parameters

  • $post (WP_Post) (Required) – The post object that these meta boxes are being generated for.

More information

See WordPress Developer Resources: register_and_do_post_meta_boxes

Examples

Registering a custom meta box

This code registers a custom meta box for posts.

function my_custom_meta_box() {
    add_meta_box(
        'my_custom_meta_box_id', // Unique ID
        'My Custom Meta Box', // Box title
        'my_custom_meta_box_callback', // Content callback
        'post' // Post type
    );
}
add_action( 'add_meta_boxes', 'my_custom_meta_box' );

function my_custom_meta_box_callback( $post ) {
    // Display the custom meta box content
    echo 'This is my custom meta box content.';
}

Saving custom meta box data

This code saves custom meta box data when a post is saved.

function my_custom_meta_box_save( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    // Save custom meta box data
    update_post_meta( $post_id, 'my_custom_meta_key', 'my_custom_meta_value' );
}
add_action( 'save_post', 'my_custom_meta_box_save' );

Displaying custom meta box data

This code displays custom meta box data on the front-end.

function my_custom_meta_box_display( $content ) {
    global $post;
    $meta_value = get_post_meta( $post->ID, 'my_custom_meta_key', true );

    return $content . '<div>My Custom Meta Value: ' . esc_html( $meta_value ) . '</div>';
}
add_filter( 'the_content', 'my_custom_meta_box_display' );

Removing a default meta box

This code removes the default “Excerpt” meta box for posts.

function my_remove_excerpt_meta_box() {
    remove_meta_box( 'postexcerpt', 'post', 'normal' );
}
add_action( 'admin_menu', 'my_remove_excerpt_meta_box' );

Moving a default meta box

This code moves the “Featured Image” meta box to a new location.

function my_move_featured_image_meta_box() {
    remove_meta_box( 'postimagediv', 'post', 'side' );
    add_meta_box( 'postimagediv', __('Featured Image'), 'post_thumbnail_meta_box', 'post', 'normal', 'high' );
}
add_action( 'do_meta_boxes', 'my_move_featured_image_meta_box' );