Tuesday, September 3, 2019

Create Custom Post Meta in Wordpress

In previous post we learnt how can we register a custom post type in wordpress. Wordpress adds some information to post type you are registering like title, editor, excerpt, comments and author etc. But what if you want to store some additional information with custom post type?

Create Custom Post Meta in Wordpress

What is Post Meta Data?

Custom post meta data is an additional piece of information which is saved separately from post. This additional information is not saved as a direct part of a post but rather linked to that post. In previous post we created a "Movies" post type. To understand post meta data we will store additional information like movie url, duration and IMDB rating.

Lets break it down in section first we will create a file post-meta.php. We will add a meta box in this file using wordpress function "add_meta_box" which adds a box to one or more screens. Next we will need to hook a function to wordpress action hook "save_post" which will save our post meta when the post is saved. Inside that function we will use "update_post_meta" to save our post meta data.
add_meta_box($id, $title, $callback, $screen = null, $context = "advanced", $priority = "default", $callback_args = null);
  • $id - (string) (Required) - ID for meta box id attribute.
  • $title - (string) (Required) - Title of meta box.
  • $callback - (callable) (Required) - The function that will actually contain the html to draw our meta box.
  • $screen- (string|array) (Optional) - The screen or screens on which meta box will be shown.
  • $context - (string) (Optional) - Context of screen where the meta box will be displayed. Possible values are "side", "normal" and "advanced". Default value is "advanced".
  • $priority - (string) (Optional) - Priority of appearance of meta box. Possible values ("default","low", "hight"). Default value is "default".
  • $callback_args- (array) (Optional) -Array of parameters  passed as a second parameter to your callback function.

post-meta.php

//-- Add a meta box to our custom post type
add_action('add_meta_boxes', 'add_movie_metas');
function add_movie_metas(){
    add_meta_box('movie_meta_box','Movie Data','draw_movie_meta',["movie"]);
}
//-- Function to draw our post meta
function draw_movie_meta($post){
    //-- Retreive post meta data if its already saved
    $movie_url      = get_post_meta($post->ID, 'movie_url', true);
    $duration       = get_post_meta($post->ID, 'duration', true);
    $imdb_rating    = get_post_meta($post->ID, 'imdb_rating', true);
    ?>
    <table class="form-table movie-form-table">
        <tbody>
            <tr>
                <th scope="row"><label for="movie_url"><?php _e("Movie URL", "textdomain")?></label></th>
                <td><input type="text" name="movie_url" id="movie_url" class="regular-text" value="<?=$movie_url?>" /></td>
            </tr>
            <tr>
                <th scope="row"><label for="duration"><?php _e("Duration", "textdomain")?></label></th>
                <td><input type="text" name="duration" id="duration" class="regular-text" value="<?=$duration?>" /></td>
            </tr>
            <tr>
                <th scope="row"><label for="imdb_rating"><?php _e("IMDB Rating", "textdomain")?></label></th>
                <td><input type="text" name="imdb_rating" id="imdb_rating" class="regular-text" value="<?=$imdb_rating?>" /></td>
            </tr>
        </tbody>
    </table>
<?php
}

add_action('save_post', 'save_movie_meta');
function save_movie_meta($post_id){
    // -- Prepare array of our post meta to loop through
    $metas = ["movie_url","duration","imdb_rating"];
    foreach($metas as $meta){
        if (isset($_POST[$meta])) {
           //-- Save post meta data if its submitted with post
           update_post_meta($post_id, $meta, esc_html($_POST[$meta]));
        }
    }

}
Now we will include this post-meta.php in our functions.php to work.
include("post-meta.php");
This is how our post meta box will look like:

Custom Post Meta