Add Meta Boxes to Post Types in WordPress

Add Meta Boxes to Post Types in WordPress

You’ve probably seen and used meta boxes if you’ve ever used WordPress to create a website for yourself or a customer, or if you work for a company whose website is powered by WordPress.

We’ve already discussed how to create custom meta boxes to WordPress. We’ll go two steps further in this article, outlining their relationship and interaction with post types, as well as how to use data saved in a meta box in the WordPress front-end.

Adding Meta Boxes to Post Types Screen

The add_meta_box() the function is used to add a meta box to any post-type editing screen, and it is then attached to the add_meta_boxes action.

A metabox is added to the post edit screen using the code below. Take note of the function global_notice_metabox_callback, which is used to display the form field(s) in the meta box. That will be discussed later.

function global_notice_metabox() {

    add_meta_box(
        'global-notice',
        __( 'Global Notice', 'themedev' ),
        'global_notice_meta_box_callback',
        'post'
    );
}

add_action( 'add_meta_boxes', 'global_notice_metabox' );

To add a meta box to a number of post types screens – postpage and a book custom post type; create an array of the post types, iterate over the array, and use add_meta_box() to add the meta box to them.

function global_notice_metabox() {

    $screens = array( 'post', 'page');

    foreach ( $screens as $screen ) {
        add_meta_box(
            'global-notice',
            __( 'Global Notice', 'themedev' ),
            'global_notice_metabox_callback',
            $screen
        );
    }
}

add_action( 'add_meta_boxes', 'global_notice_metabox' );

To add a meta box to all existing post types and those to be created in future, use get_post_types() to get an array of the post types and then replace the value of $screen above with it.

function global_notice_metabox() {

    $screens = get_post_types();

    foreach ( $screens as $screen ) {
        add_meta_box(
            'global-notice',
            __( 'Global Notice', 'themedev' ),
            'global_notice_metabox_callback',
            $screen
        );
    }
}

add_action( 'add_meta_boxes', 'global_notice_metabox' );

Adding a meta box to all existing and new post types can also be done by leaving out the third ($screen) argument like so:

function global_notice_metabox() {

    add_meta_box(
        'global-notice',
        __( 'Global Notice', 'themedev' ),
        'global_notice_metabox_callback'
    );

}

add_action( 'add_meta_boxes', 'global_notice_metabox' );

A meta box can also be restricted to a post type (book in this example) by appending the post type name to add_meta_boxes action hook as follows:

function global_notice_metabox() {

    add_meta_box(
        'global-notice',
        __( 'Global Notice', 'themedev' ),
        'global_notice_metabox_callback'
    );

}

add_action( 'add_meta_boxes_book', 'global_notice_metabox' );

Among the array of argument used by register_post_type() for customizing a custom post type is the register_meta_box_cb in which its value is a callback function that is called when setting up the meta boxes.

Say we created a book custom post type with the following code:

function themedev_book_cpt() {

    $args = array(
        'label'                => 'Books',
        'public'               => true,
        'register_meta_box_cb' => 'global_notice_metabox'
    );

    register_post_type( 'book', $args );
}

add_action( 'init', 'themedev_book_cpt' );

Adding the add_meta_box() function definition for creating a meta box inside a global_notice_metabox PHP function (value of register_meta_box_cb above) will add the meta box to the book custom post type edit screen.

And again, here is our example global_notice_metabox function

function global_notice_metabox() {

    add_meta_box(
        'global-notice',
        __( 'Global Notice', 'themedev' ),
        'global_notice_metabox_callback'
    );

}

So far, we’ve learnt how to register or add meta boxes to WordPress in a variety of ways. The global_notice_metabox _callback function, which will include the form field of our meta box, has yet to be created.

The global_notice_metabox_callback function, which includes a text area field in the meta box, is seen below.

function global_notice_metabox_callback( $post ) {

    // Add a nonce field so we can check for it later.
    wp_nonce_field( 'global_notice_nonce', 'global_notice_nonce' );

    $value = get_post_meta( $post->ID, '_global_notice', true );

    echo '<textarea style="width:100%" id="global_notice" name="global_notice">' . esc_attr( $value ) . '</textarea>';
}

The save_post action hook handles saving the data entered into the text area when the post is saved as a draft or published.

/**
 * When the post is saved, saves our custom data.
 *
 * @param int $post_id
 */
function save_global_notice_metabox_data( $post_id ) {

    // Check if our nonce is set.
    if ( ! isset( $_POST['global_notice_nonce'] ) ) {
        return;
    }

    // Verify that the nonce is valid.
    if ( ! wp_verify_nonce( $_POST['global_notice_nonce'], 'global_notice_nonce' ) ) {
        return;
    }

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

    // Check the user's permissions.
    if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {

        if ( ! current_user_can( 'edit_page', $post_id ) ) {
            return;
        }

    }
    else {

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
    }

    /* OK, it's safe for us to save the data now. */

    // Make sure that it is set.
    if ( ! isset( $_POST['global_notice'] ) ) {
        return;
    }

    // Sanitize user input.
    $my_data = sanitize_text_field( $_POST['global_notice'] );

    // Update the meta field in the database.
    update_post_meta( $post_id, '_global_notice', $my_data );
}

add_action( 'save_post', 'save_global_notice_metabox_data' );

To put the data that would be entered into the meta box text area to use, we’ll display the data before the post content that it’s saved against is displayed.

function global_notice_before_post( $content ) {

    global $post;

    // retrieve the global notice for the current post
    $global_notice = esc_attr( get_post_meta( $post->ID, '_global_notice', true ) );

    $notice = "<div class='sp_global_notice'>$global_notice</div>";

    return $notice . $content;

}

add_filter( 'the_content', 'global_notice_before_post' );

Code Explanation

First, we created a global_notice_before_post function hooked into the_content filter with a $content the parameter which contains the post content.

Inside the function, we include the global $post variable that contains the WP_Post the object of the current post that is being viewed.

The global notice saved against a given post is retrieved by get_post_meta and saved to $global_notice variable.

The notice is then wrapped in a div and saved to the $notice variable.

And finally, $notice which holds the global notice is concatenated to $content which is the actual post content.

Below is a screenshot of a post with the global notice before the post content.

Add MetaBox using NextCode without coding

NextCode is a Simple and Lightweight WordPress Options Framework for Themes and Plugins.

Built in OOP paradigm with a high number of custom fields and tons of options.
It’s highly modern and advanced framework.

Admin Options

Create A Simple and Lightweight Theme Options or Plugin Settings by NextCode, 34+ custom fields are available.

Render Theme and Plugin Styles

NextCode provide to you for style Themes and Plugins pages, there are 20+ fields are available for custom styles.

Custom PostType

Create Unlimited custom posttype for add awesome features into Themes and Plugins.

Unlimited Metabox Options

Allows you to bring custom metabox settings to all of your pages and posts. We provide advanced settings with numerious number of fields.

Taxonomy Option

Allows you to bring custom taxonomy settings to all of your categories, tags, or CPT. We provide advanced settings with numerous fields.

More details of NextCode Features

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

all-plugin
Golam Mostafa
Written by

Golam Mostafa

Golam Mostafa is a WordPress aficionado with a good sense of cinema. He enjoys reading books and playing football in his spare time.

Table of Content

Table of Contents