add_meta_box( string $id, string $title, callable $callback, string|array|WP_Screen $screen = null, string $context = 'advanced', string $priority = 'default', array $callback_args = null )

Adds a meta box to one or more screens.


Description Description


Parameters Parameters

$id

(string) (Required) Meta box ID (used in the 'id' attribute for the meta box).

$title

(string) (Required) Title of the meta box.

$callback

(callable) (Required) Function that fills the box with the desired content. The function should echo its output.

$screen

(string|array|WP_Screen) (Optional) The screen or screens on which to show the box (such as a post type, 'link', or 'comment'). Accepts a single screen ID, WP_Screen object, or array of screen IDs. Default is the current screen. If you have used add_menu_page() or add_submenu_page() to create a new screen (and hence screen_id), make sure your menu slug conforms to the limits of sanitize_key() otherwise the 'screen' menu may not correctly render on your page.

Default value: null

$context

(string) (Optional) The context within the screen where the boxes should display. Available contexts vary from screen to screen. Post edit screen contexts include 'normal', 'side', and 'advanced'. Comments screen contexts include 'normal' and 'side'. Menus meta boxes (accordion sections) all use the 'side' context. Global

Default value: 'advanced'

$priority

(string) (Optional) The priority within the context where the boxes should show ('high', 'low').

Default value: 'default'

$callback_args

(array) (Optional) Data that should be set as the $args property of the box array (which is the second parameter passed to your callback).

Default value: null


Top ↑

Source Source

File: wp-admin/includes/template.php

function add_meta_box( $id, $title, $callback, $screen = null, $context = 'advanced', $priority = 'default', $callback_args = null ) {
	global $wp_meta_boxes;

	if ( empty( $screen ) ) {
		$screen = get_current_screen();
	} elseif ( is_string( $screen ) ) {
		$screen = convert_to_screen( $screen );
	} elseif ( is_array( $screen ) ) {
		foreach ( $screen as $single_screen ) {
			add_meta_box( $id, $title, $callback, $single_screen, $context, $priority, $callback_args );
		}
	}

	if ( ! isset( $screen->id ) ) {
		return;
	}

	$page = $screen->id;

	if ( ! isset( $wp_meta_boxes ) ) {
		$wp_meta_boxes = array();
	}
	if ( ! isset( $wp_meta_boxes[ $page ] ) ) {
		$wp_meta_boxes[ $page ] = array();
	}
	if ( ! isset( $wp_meta_boxes[ $page ][ $context ] ) ) {
		$wp_meta_boxes[ $page ][ $context ] = array();
	}

	foreach ( array_keys( $wp_meta_boxes[ $page ] ) as $a_context ) {
		foreach ( array( 'high', 'core', 'default', 'low' ) as $a_priority ) {
			if ( ! isset( $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ] ) ) {
				continue;
			}

			// If a core box was previously added or removed by a plugin, don't add.
			if ( 'core' == $priority ) {
				// If core box previously deleted, don't add
				if ( false === $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ] ) {
					return;
				}

				/*
				 * If box was added with default priority, give it core priority to
				 * maintain sort order.
				 */
				if ( 'default' == $a_priority ) {
					$wp_meta_boxes[ $page ][ $a_context ]['core'][ $id ] = $wp_meta_boxes[ $page ][ $a_context ]['default'][ $id ];
					unset( $wp_meta_boxes[ $page ][ $a_context ]['default'][ $id ] );
				}
				return;
			}
			// If no priority given and id already present, use existing priority.
			if ( empty( $priority ) ) {
				$priority = $a_priority;
				/*
				* Else, if we're adding to the sorted priority, we don't know the title
				* or callback. Grab them from the previously added context/priority.
				*/
			} elseif ( 'sorted' == $priority ) {
				$title         = $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ]['title'];
				$callback      = $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ]['callback'];
				$callback_args = $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ]['args'];
			}
			// An id can be in only one priority and one context.
			if ( $priority != $a_priority || $context != $a_context ) {
				unset( $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ] );
			}
		}
	}

	if ( empty( $priority ) ) {
		$priority = 'low';
	}

	if ( ! isset( $wp_meta_boxes[ $page ][ $context ][ $priority ] ) ) {
		$wp_meta_boxes[ $page ][ $context ][ $priority ] = array();
	}

	$wp_meta_boxes[ $page ][ $context ][ $priority ][ $id ] = array(
		'id'       => $id,
		'title'    => $title,
		'callback' => $callback,
		'args'     => $callback_args,
	);
}

Top ↑

Changelog Changelog

Changelog
Version Description
4.4.0 The $screen parameter now accepts an array of screen IDs.
2.5.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Drew Jaynes
    /**
     * Register meta box(es).
     */
    function wpdocs_register_meta_boxes() {
    	add_meta_box( 'meta-box-id', __( 'My Meta Box', 'textdomain' ), 'wpdocs_my_display_callback', 'post' );
    }
    add_action( 'add_meta_boxes', 'wpdocs_register_meta_boxes' );
    
    /**
     * Meta box display callback.
     *
     * @param WP_Post $post Current post object.
     */
    function wpdocs_my_display_callback( $post ) {
    	// Display code/markup goes here. Don't forget to include nonces!
    }
    
    /**
     * Save meta box content.
     *
     * @param int $post_id Post ID
     */
    function wpdocs_save_meta_box( $post_id ) {
    	// Save logic goes here. Don't forget to include nonce checks!
    }
    add_action( 'save_post', 'wpdocs_save_meta_box' );
    
  2. Skip to note 2 content
    Contributed by Codex

    Class
    This is an example of how to add a meta box from inside a class

    /**
     * Calls the class on the post edit screen.
     */
    function call_someClass() {
    	new someClass();
    }
    
    if ( is_admin() ) {
    	add_action( 'load-post.php',     'call_someClass' );
    	add_action( 'load-post-new.php', 'call_someClass' );
    }
    
    /**
     * The Class.
     */
    class someClass {
    
    	/**
    	 * Hook into the appropriate actions when the class is constructed.
    	 */
    	public function __construct() {
    		add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
    		add_action( 'save_post',      array( $this, 'save'         ) );
    	}
    
    	/**
    	 * Adds the meta box container.
    	 */
    	public function add_meta_box( $post_type ) {
    		// Limit meta box to certain post types.
    		$post_types = array( 'post', 'page' );
    
    		if ( in_array( $post_type, $post_types ) ) {
    			add_meta_box(
    				'some_meta_box_name',
    				__( 'Some Meta Box Headline', 'textdomain' ),
    				array( $this, 'render_meta_box_content' ),
    				$post_type,
    				'advanced',
    				'high'
    			);
    		}
    	}
    
    	/**
    	 * Save the meta when the post is saved.
    	 *
    	 * @param int $post_id The ID of the post being saved.
    	 */
    	public function save( $post_id ) {
    
    		/*
    		 * We need to verify this came from the our screen and with proper authorization,
    		 * because save_post can be triggered at other times.
    		 */
    
    		// Check if our nonce is set.
    		if ( ! isset( $_POST['myplugin_inner_custom_box_nonce'] ) ) {
    			return $post_id;
    		}
    
    		$nonce = $_POST['myplugin_inner_custom_box_nonce'];
    
    		// Verify that the nonce is valid.
    		if ( ! wp_verify_nonce( $nonce, 'myplugin_inner_custom_box' ) ) {
    			return $post_id;
    		}
    
    		/*
    		 * If this is an autosave, our form has not been submitted,
    		 * so we don't want to do anything.
    		 */
    		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
    			return $post_id;
    		}
    
    		// Check the user's permissions.
    		if ( 'page' == $_POST['post_type'] ) {
    			if ( ! current_user_can( 'edit_page', $post_id ) ) {
    				return $post_id;
    			}
    		} else {
    			if ( ! current_user_can( 'edit_post', $post_id ) ) {
    				return $post_id;
    			}
    		}
    
    		/* OK, it's safe for us to save the data now. */
    
    		// Sanitize the user input.
    		$mydata = sanitize_text_field( $_POST['myplugin_new_field'] );
    
    		// Update the meta field.
    		update_post_meta( $post_id, '_my_meta_value_key', $mydata );
    	}
    
    
    	/**
    	 * Render Meta Box content.
    	 *
    	 * @param WP_Post $post The post object.
    	 */
    	public function render_meta_box_content( $post ) {
    
    		// Add an nonce field so we can check for it later.
    		wp_nonce_field( 'myplugin_inner_custom_box', 'myplugin_inner_custom_box_nonce' );
    
    		// Use get_post_meta to retrieve an existing value from the database.
    		$value = get_post_meta( $post->ID, '_my_meta_value_key', true );
    
    		// Display the form, using the current value.
    		?>
    		<label for="myplugin_new_field">
    			<?php _e( 'Description for this field', 'textdomain' ); ?>
    		</label>
    		<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="<?php echo esc_attr( $value ); ?>" size="25" />
    		<?php
    	}
    }
    
  3. Skip to note 3 content
    Contributed by wpdevco
    /**
     * Register a meta box using a class.
     */
    class WPDocs_Custom_Meta_Box {
    
    	/**
    	 * Constructor.
    	 */
    	public function __construct() {
    		if ( is_admin() ) {
    			add_action( 'load-post.php',     array( $this, 'init_metabox' ) );
    			add_action( 'load-post-new.php', array( $this, 'init_metabox' ) );
    		}
    
    	}
    
    	/**
    	 * Meta box initialization.
    	 */
    	public function init_metabox() {
    		add_action( 'add_meta_boxes', array( $this, 'add_metabox'  )        );
    		add_action( 'save_post',      array( $this, 'save_metabox' ), 10, 2 );
    	}
    
    	/**
    	 * Adds the meta box.
    	 */
    	public function add_metabox() {
    		add_meta_box(
    			'my-meta-box',
    			__( 'My Meta Box', 'textdomain' ),
    			array( $this, 'render_metabox' ),
    			'post',
    			'advanced',
    			'default'
    		);
    
    	}
    
    	/**
    	 * Renders the meta box.
    	 */
    	public function render_metabox( $post ) {
    		// Add nonce for security and authentication.
    		wp_nonce_field( 'custom_nonce_action', 'custom_nonce' );
    	}
    
    	/**
    	 * Handles saving the meta box.
    	 *
    	 * @param int     $post_id Post ID.
    	 * @param WP_Post $post    Post object.
    	 * @return null
    	 */
    	public function save_metabox( $post_id, $post ) {
    		// Add nonce for security and authentication.
    		$nonce_name   = isset( $_POST['custom_nonce'] ) ? $_POST['custom_nonce'] : '';
    		$nonce_action = 'custom_nonce_action';
    
    		// Check if nonce is valid.
    		if ( ! wp_verify_nonce( $nonce_name, $nonce_action ) ) {
    			return;
    		}
    
    		// Check if user has permissions to save data.
    		if ( ! current_user_can( 'edit_post', $post_id ) ) {
    			return;
    		}
    
    		// Check if not an autosave.
    		if ( wp_is_post_autosave( $post_id ) ) {
    			return;
    		}
    
    		// Check if not a revision.
    		if ( wp_is_post_revision( $post_id ) ) {
    			return;
    		}
    	}
    }
    
    new WPDocs_Custom_Meta_Box();
    
  4. Skip to note 4 content
    Contributed by Codex

    Callback args

    The $callback_args array will be passed to the callback function as the second argument. The first argument is the post’s $post object.

    /**
     * This function adds a meta box with a callback function of my_metabox_callback()
     */
    function add_wpdocs_meta_box() {
    	$var1 = 'this';
    	$var2 = 'that';
    	add_meta_box(
    		'metabox_id',
    		__( 'Metabox Title', 'textdomain' ),
    		'wpdocs_metabox_callback',
    		'page',
    		'normal',
    		'low',
    		array( 'foo' => $var1, 'bar' => $var2 )
    	);
    }
    
    /**
     * Get post meta in a callback
     *
     * @param WP_Post $post    The current post.
     * @param array   $metabox With metabox id, title, callback, and args elements.
     */
    
    function wpdocs_metabox_callback( $post, $metabox ) {
    	// Output last time the post was modified.
    	echo 'Last Modified: ' . $post->post_modified;
    
    	// Output 'this'.
    	echo $metabox['args']['foo'];
    
    	// Output 'that'.
    	echo $metabox['args']['bar'];
    
    	// Output value of custom field.
    	echo get_post_meta( $post->ID, 'wpdocs_custom_field', true );
    }
    
  5. Skip to note 5 content
    Contributed by obiPlabon

    This is the way to register menu screen metabox :)

    function op_register_menu_meta_box() {
        add_meta_box(
            'op-menu-meta-box-id',
            esc_html__( 'Op Menu MetaBox Title', 'text-domain' ),
            'op_render_menu_meta_box',
            'nav-menus',
            'side',
            'core'
            );
    }
    add_action( 'load-nav-menus.php', 'op_register_menu_meta_box' );
    
    function op_render_menu_meta_box() {
        // Metabox content
        echo '<strong>Hi, I am MetaBox.</strong>';
    }
    
  6. Skip to note 6 content
    Contributed by David

    An often forgotten, but also very important, fact is that any save_post handler should check for a multisite switched context. Here’s an example of such guard:

    <?php
    namespace DevWpNote\MetaBox;
    
    add_action( 'save_post', __NAMESPACE_ . '\save_fields', 10, 3 );
    function save_fields( $post_id, WP_Post $post, $update ) {
       // check nonce ...
       // check autosave ... 
       // check user capabilities ...
    
       // check if there was a multisite switch before
       if ( is_multisite() && ms_is_switched() ) {
          return $post_id;
       }
    
       // handle your meta box input ...
    }
    

    That ensures compatibility with other plugins that uses switch_to_blog() while they are working on the save_post hook. If they are calling wp_insert_post() again on other sites, your code would overwrite the wrong content without this check.

  7. Skip to note 8 content
    Contributed by Rubel Miah
    //Register Meta Box
    function rm_register_meta_box() {
    	add_meta_box( 'rm-meta-box-id', esc_html__( 'RM MetaBox Title', 'text-domain' ), 'rm_meta_box_callback', 'post', 'advanced', 'high' );
    }
    add_action( 'add_meta_boxes', 'rm_register_meta_box');
    
    //Add field
    function rm_meta_box_callback( $meta_id ) {
    
    	$outline = '<label for="title_field" style="width:150px; display:inline-block;">'. esc_html__('Title Field', 'text-domain') .'</label>';
    	$title_field = get_post_meta( $meta_id->ID, 'title_field', true );
    	$outline .= '<input type="text" name="title_field" id="title_field" class="title_field" value="'. esc_attr($title_field) .'" style="width:300px;"/>';
    
    	echo $outline;
    }
  8. Skip to note 9 content

    Slight gotcha for comments metabox

    If you need to add a metabox to the comment edit screen, you have to pass in the value ‘normal‘ for the $context parameter.

    // This will NOT work
    add_meta_box( 
    	'my_comment_metabox_1',      // ID
    	__('My comment metabox 1' ), // Title
    	'prefix_comment_metabox',    // Callback
    	'comment' 					 // Screen
    );
    // This WILL work. Same call, but with 'normal' for context instead of default 'advanced'
    add_meta_box( 
    	'my_comment_metabox_2', 	  // ID
    	__('My comment metabox 2' ),  // Title 
    	'prefix_comment_metabox', 	  // Callback
    	'comment', 					  // Screen
    	'normal' 					  // Context
    );
    
    
  9. Skip to note 10 content
    Contributed by Kuba Mikita

    This is how the metabox data should be processed in the save_post action.

    function save_metabox_callback( $post_id ) {
    
    	if ( ! isset( $_POST['nonce'] ) ) {
    		return;
    	}
    
    	if ( ! wp_verify_nonce( $_POST['nonce'], 'nonce_value' ) ) {
    		return;
    	}
    
    	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
    		return;
    	}
    
    	if ( ! current_user_can( 'edit_post', $post_id ) ) {
    		return;
    	}
    
    	if ( isset( $_POST['post_type'] ) && 'page' === $_POST['post_type'] ) {
    
    		// do stuff
    
    	}
    
    	// Check if $_POST field(s) are available
    
    	// Sanitize
    
    	// Save
    	
    }
    add_action( 'save_post', 'save_metabox_callback' );
    
  10. Skip to note 13 content
    Contributed by slamorte

    From WordPress 4.4 the $screen arg can be an array, which greatly simplifies mass additions or alterations of meta boxes. The following code changes the title of the “Author” meta box to “Editor” on pages, posts, attachments, and all custom post types no matter how many are added or when they are added to your site.

    add_action( 'do_meta_boxes', 'my_customize_meta_boxes'); //do_meta_boxes also allows plugin metaboxes to be modified
    function my_customize_meta_boxes(){
        $post_types = get_post_types();
        remove_meta_box( 'authordiv', $post_types, 'normal' );
    
        add_meta_box( 'authordiv', __( 'Editor', 'textdomain' ), 'post_author_meta_box', $post_types, 'side', 'default' );
    }
    
  11. Skip to note 14 content
    Contributed by Ashok

    This is how it can be called within a class:

    
    class MyClass{
        
        public function __construct() {
            add_action( 'add_meta_boxes', array( &$this, 'wpdocs_register_meta_boxes' ) );
            // If static
            add_action( 'add_meta_boxes', array( __CLASS__, 'wpdocs_register_meta_boxes_static' ) );
        }
        
        // Singleton
        static function get_instance() {
            static $Inst = null;
            if( $Inst == null ) {
                $Inst = new self();
            }
            
            return $Inst;
        }
        
        public function wpdocs_register_meta_boxes() {
            add_meta_box( 'meta-box-id', __( 'My Meta Box', 'textdomain' ), 'wpdocs_my_display_callback', 'post' );
        }
        
        public function wpdocs_register_meta_boxes_static() {
            add_meta_box( 'meta-box-id', __( 'My Meta Box', 'textdomain' ), 'wpdocs_my_display_callback', 'post' );
        }
        
    }
    
    MyClass::get_instance();
    
    
  12. Skip to note 15 content
    Contributed by designdrumm

    You have $screen = null in the function call but no check and balances for if it IS null. This was causing an error warning when error logging was turned on.

    function add_meta_box( $id, $title, $callback, $screen = null, $context = 'advanced', $priority = 'default', $callback_args = null ) {
        global $wp_meta_boxes;
     
        if ( empty( $screen ) ) {
            $screen = get_current_screen();
        } elseif ( is_string( $screen ) ) {
            $screen = convert_to_screen( $screen );
        } elseif ( is_array( $screen ) ) {
            foreach ( $screen as $single_screen ) {
                add_meta_box( $id, $title, $callback, $single_screen, $context, $priority, $callback_args );
            }
        }
     
        if ( ! isset( $screen->id ) ) {
            return;
        }
     
        $page = $screen->id;
    
    … 

    should be replaced with..

    function add_meta_box( $id, $title, $callback, $screen = null, $context = 'advanced', $priority = 'default', $callback_args = null ) {
    	global $wp_meta_boxes;
    
    	if ( $screen == null ) {
    $screen = WP_Screen::get( );
    } elseif ( empty( $screen ) ) {
    $screen = get_current_screen();
    } elseif ( is_string( $screen ) ) {
    $screen = convert_to_screen( $screen );
    } elseif ( is_array( $screen ) ) {
    foreach ( $screen as $single_screen ) {
    add_meta_box( $id, $title, $callback, $single_screen, $context, $priority, $callback_args );
    }
    }
    
    $page = $screen->id;
    
    … 

    not

    if ( ! isset( $screen->id ) ) {
            return;
        }

    IMHO

    Best,
    Design Drumm

You must log in before being able to contribute a note or feedback.