How To Creating a custom Meta Box In WordPress

[easy-social-share counters=0 style="button"]

add_meta_box function would be used to create custom meta boxes. This function can only be responsible for registering or showing custom meta boxes.

There is the code to insert a custom meta box to WordPress posts:

function custom_meta_box_markup()

{



}



function add_custom_meta_box()

{

    add_meta_box("demo-meta-box", "Custom Meta Box", "custom_meta_box_markup", "post", "side", "high", null);

}



add_action("add_meta_boxes", "add_custom_meta_box");

add_meta_box must be known as inside add_meta_boxes hook up .

add_meta_box requires seven suggestions . Here I will discuss the number of suggestions :

  1. $id: Each and every Meta box is identified by Word Press uniquely using it is id. Provide an id or make sure you prefix it to prevent overriding.
  2. $title: Title of the Meta box on the admin interface.
  3. $callback: add_meta_box calls the callback to show the contents of the custom Meta box.
  4. $screen: It is useful to instruct Word Press by which display to show the Meta box. Possible considers are “post” , “page“, “dashboard” , “link” , “attachment” and “custom_post_type” id . In the above for example we are now adding the custom Meta box to Word Press posts display.
  5. $context: It is useful to provide the position of the custom Meta on the computer screen. Possible considers are “normal“, “advanced” or “side”. In the above for example we positioned the Meta box on side.
  6. $priority: It is useful to provide the position of the box in the provided context. Possible values are “high”, “core”, “default”, and then “low”. In the above for example we positioned the Meta box
  7. $callback_args: It is useful to provide arguments to the callback function.

The following shows how the meta box styles:

Right here, the custom meta box content is empty simply because we haven’t as yet heavily populated the content.

Displaying Fields in a Custom Meta Box

For showing idea we will insert a text input, drop down or a checkbox form area to the custom meta box.

Below is the code:

function custom_meta_box_markup($object)

{

    wp_nonce_field(basename(__FILE__), "meta-box-nonce");



    ?>

        <div>

            <label for="meta-box-text">Text</label>

            <input name="meta-box-text" type="text" value="<?php echo get_post_meta($object->ID, "meta-box-text", true); ?>">



            <br>



            <label for="meta-box-dropdown">Dropdown</label>

            <select name="meta-box-dropdown">

                <?php

                    $option_values = array(1, 2, 3);



                    foreach($option_values as $key => $value)

                    {

                        if($value == get_post_meta($object->ID, "meta-box-dropdown", true))

                        {

                            ?>

                                <option selected><?php echo $value; ?></option>

                            <?php   

                        }

                        else

                        {

                            ?>

                                <option><?php echo $value; ?></option>

                            <?php

                        }

                    }

                ?>

            </select>



            <br>



            <label for="meta-box-checkbox">Check Box</label>

            <?php

                $checkbox_value = get_post_meta($object->ID, "meta-box-checkbox", true);



                if($checkbox_value == "")

                {

                    ?>

                        <input name="meta-box-checkbox" type="checkbox" value="true">

                    <?php

                }

                else if($checkbox_value == "true")

                {

                    ?> 

                        <input name="meta-box-checkbox" type="checkbox" value="true" checked>

                    <?php

                }

            ?>

        </div>

    <?php 

}

This is how the code is working:

  • 1st we set up the nonce area so we can prevent CSRF attack in case the form is published.
  • get_post_meta would be used to retrieve meta data from the data-base. In case not any such as meta data is available, it returns an empty string. In case your user has already submitted the form already, and then we using the meta data saved in data-base. Other-wise, we move to the default value.

This is how the meta box look right now:

1424173490custom-meta-box-2-1024x519

Storing Meta Data

Right now we will need to retail store the custom meta data whenever a user register the form; will need to save the post.

This is the code to save meta data whenever a user clicks on the ‘save draft’ or simply ‘publish’ key:

function save_custom_meta_box($post_id, $post, $update)

{

    if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__)))

        return $post_id;



    if(!current_user_can("edit_post", $post_id))

        return $post_id;



    if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)

        return $post_id;



    $slug = "post";

    if($slug != $post->post_type)

        return $post_id;



    $meta_box_text_value = "";

    $meta_box_dropdown_value = "";

    $meta_box_checkbox_value = "";



    if(isset($_POST["meta-box-text"]))

    {

        $meta_box_text_value = $_POST["meta-box-text"];

    }  

    update_post_meta($post_id, "meta-box-text", $meta_box_text_value);



    if(isset($_POST["meta-box-dropdown"]))

    {

        $meta_box_dropdown_value = $_POST["meta-box-dropdown"];

    }  

    update_post_meta($post_id, "meta-box-dropdown", $meta_box_dropdown_value);



    if(isset($_POST["meta-box-checkbox"]))

    {

        $meta_box_checkbox_value = $_POST["meta-box-checkbox"];

    }  

    update_post_meta($post_id, "meta-box-checkbox", $meta_box_checkbox_value);

}



add_action("save_post", "save_custom_meta_box", 10, 3);

That is the way the code is working:
– save post hook’s callback is triggered in case a post, page or custom post type is saved. We attached a callback to save Meta data.
– We verify the nonce. In case the nonce is not present and invalid and then we don’t save you the go back the callback.
– We check out whether the current logged in admin user has access to save Meta data for the post type. In case the user doesn’t get approval, after that we go back the callback.
– We look at in case the post will be self saved. In case the save is self saved, after that we go back the callback.
– Last see is whether the post type is just like the Meta box post type. Or else, and then we go back the callback.
– We retrieve the considers of the form areas using PHP $_POST variable and then save all of them in data-base by using update_post_meta create a new meta data key/value in the data-base in case the key element is not present, other-wise it notifications the key value.

Removing a Meta Box 

We can easily remove custom Meta boxes so the default Word Press basic core Meta boxes using remove_metabox. To remove a Metal box that you need it is ID, display or articles.

Here I will discuss the IDs of those all important default Meta boxes:

  • ‘authordiv’ – Author metabox
  • ‘categorydiv’ – Categories metabox
  • ‘commentstatusdiv’ – Comments status metabox (discussion)
  • ‘commentsdiv’ – Comments metabox
  • ‘formatdiv’ – Formats metabox
  • ‘pageparentdiv’ – Attributes metabox
  • ‘postcustom’ – Custom fields metabox
  • ‘postexcerpt’ – Excerpt metabox
  • ‘postimagediv’ – Featured image metabox
  • ‘revisionsdiv’ – Revisions metabox
  • ‘slugdiv’ – Slug metabox
  • ‘submitdiv’ – Date, status, and update/save metabox
  • ‘tagsdiv-post_tag’ – Tags metabox
  • ‘{$tax-name}div’ – Hierarchical custom taxonomies metabox
  • ‘trackbacksdiv’ – Trackbacks metabox

There is the code to remove custom fields meta box:

function remove_custom_field_meta_box()

{

    remove_meta_box("postcustom", "post", "normal");

}

add_action("do_meta_boxes", "remove_custom_field_meta_box");

Right here we triggered remove_meta_box in do_meta_boxes hook up. But the truth is can not at all times call on remove_meta_box inside it. As an example, to remove dashboard widgets you will need to call it inside wp_dashboard_setup hook up.

Submit a comment

Pin It on Pinterest