add_meta_box() wordpress function and usage This text is not used because the data attribute has a value

add_meta_box() wordpress function and usage

Home / WordPress / WordPress Wiki / add_meta_box() wordpress function and usage

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.

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 box 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 box should show. Accepts ‘high’, ‘core’, ‘default’, or ‘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

Sample Usage

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
    }
}
/**
 * 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.
 *
/**
 * 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();

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 );
}

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>';
}

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments