Function and usage of do_meta_boxes() in wordpress


Answers ( 1 )


    The do_meta_boxes() function in WordPress is a crucial function for managing meta boxes within the WordPress admin interface. This function is used to output meta boxes for a given screen and context. Here's a detailed explanation of its function and a sample usage:


    • Name: do_meta_boxes()
    • Purpose: This function is used to display meta boxes on a given screen (like a post edit screen, a dashboard, etc.). It's a part of the WordPress template system and is commonly used by developers to add custom fields and information to WordPress edit screens.


    1. $screen (string | WP_Screen) [required]:

      • Description: This parameter specifies the screen or page on which the meta boxes should be displayed.
      • Usage: The $screen can be a string or a WP_Screen object. If you're adding a meta box to a custom page or post type, make sure your menu slug adheres to the sanitize_key() limits.
    2. $context (string) [required]:

      • Description: This parameter determines the part of the page where the meta boxes should be shown. Common values are 'normal', 'side', and 'advanced'.
      • Usage: The context helps in positioning the meta boxes in the right area of the admin screen.
    3. $data_object (mixed) [required]:

      • Description: This parameter is passed to the callback function of the meta box. It often holds the object that is the focus of the current screen.
      • Usage: In most cases, this is a WP_Post or WP_Comment object, depending on what the screen is handling.

    Return Value:

    • Type: int
    • Description: The function returns the number of meta boxes that were output for the given screen and context.

    Sample Usage:

    // Assume you have a custom post type 'my_custom_post'
    add_action('add_meta_boxes', 'add_custom_meta_boxes');
    function add_custom_meta_boxes() {
        add_meta_box('my_meta_box_id', 'My Custom Meta Box', 'my_meta_box_callback', 'my_custom_post', 'normal', 'default');
    function my_meta_box_callback($post) {
        // Display code for meta box
    // In your screen rendering function
    function render_my_custom_post_screen() {
        global $post;
        do_meta_boxes('my_custom_post', 'normal', $post);

    In this example, a meta box is added to a custom post type my_custom_post with add_meta_boxes hook. The do_meta_boxes() function is then used to render this meta box on the custom post type's edit screen in the 'normal' context, passing the global $post object as the data object.

Leave an answer