WordPress custom meta box

For custom meta box, we have to learn first custom field. Custom meta box is based on custom field.

Custom Field:

To add a custom field in wordpress we need to use get_post_meta(postId, fieldId, true) inside while loop.

<h1>Favourite item: <?php echo get_post_meta(get_the_ID(), 'fav-item', true); ?></h1>

or using $post->ID

<h1>Our favourite item: <?php echo get_post_meta($post->ID, 'fav-item', true); ?></h1>

when we write a post, we have to add a custom field and put the ‘fav-item’ as ID and also assign a value as meta data as following.

Untitled

Custom field has a disadvantage that, end user will find it tough to write the field id. thats why we need Custom Meta Box

Custom Meta Box:

The following is the code to add a cmb

// meta box

function favorite_food_show_korbo(){
    add_meta_box(
            'favorite_food_meta_box',
            'What is your fav food',
            'meta_box_er_output',
            'post',
            'normal'
            );
}

add_action('add_meta_boxes', 'favorite_food_show_korbo');

function meta_box_er_output($post){ ?>

<label for="food">Type your fav food:</label>
<p><input type="text" name="favorite" id="food" class="widefat" value="<?php echo get_post_meta($post->ID, 'favorite', true); ?>"/></p>

    
<?php }

function database_a_pathabo($post_id){
    update_post_meta($post_id, 'favorite', $_POST['favorite']);
}
add_action('save_post', 'database_a_pathabo');

now to show the value of that box just write these code inside the while loop of post viewing page.

<?php echo get_post_meta($post->ID, 'favorite', true); ?>

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *