QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads WordPress Custom Meta Boxes Tutorial

WordPress Custom Meta Boxes Tutorial

wordpress-fields-metaboxes

This post is a part 2 of Creating a WordPress Admin Theme post series.

In this post we will learn how to add custom meta boxes to wordpress posts, pages and custom post types. Custom fields are limited to key/value pairs. But meta boxes can provide much more functionality like color picker, email field, date picker etc. Meta boxes can provide all kinds form fields.


What is Meta Boxes?

Meta Box is a draggable area with some form fields in admin new/edit post screen. Some meta boxes like WYSIWYG editor, set featured image, post format, custom fields etc are wordpress provided meta boxes. We can create our own meta boxes called as custom meta boxes. Custom meta boxes can be used to increase the information attached with a particular post.

add_meta_box() function

We can create custom meta boxes using add_meta_box() function. This function can be called inside your theme(functions.php file) or your plugin.

This function should be attached to the add_meta_boxes action. add_meta_boxes action is responsible for rendering the custom meta boxes.

Adding, Deleting, Updating and Retrieving Meta Data

Data associated with the custom meta box is called meta data. WordPress provides us several different functions to operate on meta data.

We can add meta data to the DBMS using add_post_meta().

We can delete the meta data from the DBMS using delete_post_meta().

We can update the meta data in the DBMS using update_post_meta().

We can retrieve the meta data from the DBMS using get_post_meta().

Adding E-Mail Information To WordPress Posts

Let’s see an example to add a email field to wordpress posts using custom meta boxes.

<?php
    /* Called by save_post action to save meta data in database. */
    function save_my_custom_meta_box($post_id,  $post, $update)/*$post contains info about the post and $post_id is assigned to the id of the post*/
    {
        /* Verify the nonce before proceeding. For security */
        if (!isset($_POST["qnimate-email-nonce"]) || !wp_verify_nonce($_POST["qnimate-email-nonce"], basename(__FILE__)))
          return $post_id;
     
        /* Check if the current user has permission to edit the post. For security */
        if(!current_user_can("edit_post", $post_id))
            return $post_id;

        //check if it is autosave
        if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
            return $post_id;

        //check if the post type is correct
        $slug = "post";
        if($slug != $post->post_type)
            return;


        /* Store the user enter value in a variable */
        $user_entered_email_value = "";
        if(isset($_POST["author-email"]))
        {
            $user_entered_email_value = $_POST["author-email"];
        }
        else
        {
            $user_entered_email_value = "";
        }
        update_post_meta($post_id, "author-email", $user_entered_email_value);
    }




    /*Callback*/
    function meta_box_markup($object)/*$object conatins the information about the post*/
    {
        /*nonce for security purpose. more on it at http://codex.wordpress.org/WordPress_Nonces */
        wp_nonce_field(basename(__FILE__), 'qnimate-email-nonce');




        ?>
            <!-- Markup inside the custom meta box -->
            <div>
                <label for="author-email">E-Mail Of Author</label>
                <!-- Retrieve the email from database. If not yet set then empty string is returned. -->
                <input name="author-email" type="email" validate="true" value="<?php echo get_post_meta($object->ID, "author-email", true); ?>">
            </div>
        <?php
    }




    function my_custom_meta_box()
    {
        /*
        Parameters for add_meta_box() are $id, $title, $callback, $page, $context, $priority, $callback_args
        -> $id is a unqiue id given to every meta box
        -> $title is the title displayed in custom meta box
        -> $callback is a function that outputs markup inside the custom meta box
        -> $page respresents the admin page on which the mata box will be displayed on. It can be page, post, custom post type
        -> $context respresents the postiton of the meta box. It can be normal, advanced or side.
        -> $priority is the position of the box insde the context. It can be high, core, default or low
        -> $cannback_args is used to pass arguements to the callback function.
        */

        add_meta_box("qnimate-meta-box", "Author Information", "meta_box_markup", "post", "normal", "default", null);
    }




    /* This action is responsibe for creating and displaying meta boxes */
    add_action("add_meta_boxes", "my_custom_meta_box");




    /* Used to store the meta data in database */
    add_action("save_post", "save_my_custom_meta_box", 10, 3);
?>

This is the output of the above code
custom-meta-box

Similarly you can add very advanced form field to custom meta boxes. Here I created meta box for wordpress posts but they can be created for pages and custom post types also.

Conclusion

I provided a perfect, short and security proof example of custom meta box. They are more handy than wordpress custom fields. Thanks for reading. Leave comments.

Jun 9, 2014Narayan Prusty
Responsive Typography TechniquesHow To Detect Element Entered Viewport
Comments: 0

    Leave a Reply Cancel reply

    To create code blocks or other preformatted text, indent by four spaces:

        This will be displayed in a monospaced font. The first four
        spaces will be stripped off, but all other whitespace
        will be preserved.
        
        Markdown is turned off in code blocks:
         [This is not a link](http://example.com)
    

    To create not a block, but an inline code span, use backticks:

    Here is some inline `code`.

    For more help see http://daringfireball.net/projects/markdown/syntax

    Narayan Prusty

    I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

    Image8 years ago 2 Comments WordPress
    Share this
    0
    GooglePlus
    0
    Facebook
    0
    Twitter
    0
    Linkedin
    • What is Meta Boxes?
    • add_meta_box() function
    • Adding, Deleting, Updating and Retrieving Meta Data
    • Adding E-Mail Information To WordPress Posts
    Related Articles
    • Designing WordPress Posts UI For Post Formats
    • Add and Remove Widgets in WordPress Dashboard
    • WordPress Post Series Plugin
    • Get Excerpt in WordPress
    • Customizing WordPress Admin Profile Page
    Our Sponsor
    My Books

    2014 - 2015 © QNimate
    All tutorials MIT license