Add Custom Metabox in WordPress

Published on : April 27, 2026

Author:

Category: Wordpress


Custom metabox is a popular input system for WordPress. Here follow some small steps and  you can use it in your WordPress site.

[sourcecode]add_meta_boxes()[/sourcecode]

is a function which is used for the add custom metabox.

[sourcecode]
<?php
add_meta_box( $id, $title, $callback, $post_type, $context, $priority, $callback_args );
?>
[/sourcecode]

You can find the more details in here.

Now we can create a metabox which can input url with every post. For page $post_type is changed to page. For custom post type I will be custom_post_type_name.

[sourcecode]
$post_type=’post’;

$post_type=’page’;

$post_type=’custom_post_type name’;
[/sourcecode]
[sourcecode]<span style="font-family: Georgia, ‘Times New Roman’, ‘Bitstream Charter’, Times, serif; font-size: 13px; line-height: 19px;">url_meta_box_cb()</span>[sourcecode] <span style="font-family: Georgia, ‘Times New Roman’, ‘Bitstream Charter’, Times, serif; font-size: 13px; line-height: 19px;">is used for display the input form in the admin panel.</span>
[sourcecode]price_meta_box_save()[sourcecode]<span style="font-family: Georgia, ‘Times New Roman’, ‘Bitstream Charter’, Times, serif; font-size: 13px; line-height: 19px;"> is used for the auto save, save and edit the content. </span>
<span style="font-family: Georgia, ‘Times New Roman’, ‘Bitstream Charter’, Times, serif; font-size: 13px; line-height: 19px;">Add this code in the theme function.php file. Then the custom metabox show in your site.</span>
<strong><span style="font-family: Georgia, ‘Times New Roman’, ‘Bitstream Charter’, Times, serif; font-size: 13px; line-height: 19px;">Full code:</span></strong>
[sourcecode]
<?php

add_action( ‘add_meta_boxes’, ‘url_meta_box_add’ );

function url_meta_box_add() {

add_meta_box( ‘meta-box-id’, ‘Put preview URL Here!’, ‘url_meta_box_cb’, ‘post’, ‘side’, ‘high’ );

}

function url_meta_box_cb() {

wp_nonce_field( basename( __FILE__ ), ‘url_meta_box_nonce’ );

$value = get_post_meta(get_the_ID(), ‘url_key’, true);

$html = ‘<label>Url: </label><input type="text" name="url" value="’.$value.’"/>’;

echo $html;

}

add_action( ‘save_post’, ‘price_meta_box_save’ );

function price_meta_box_save( $post_id ){

if( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE ) return;

if ( !isset( $_POST[‘url_meta_box_nonce’] ) || !wp_verify_nonce( $_POST[‘url_meta_box_nonce’], basename( __FILE__ ) ) ) return;

if( !current_user_can( ‘edit_post’ ) ) return;

if( isset( $_POST[‘url’] ) )

update_post_meta( $post_id, ‘url_key’, esc_attr( $_POST[‘url’], $allowed ) );

}

?>
[/sourcecode]

To print this input in your post use this code:-

[sourcecode]
<?php

if(strlen(get_post_meta(get_the_ID(), ‘price_key’, true))>1){

echo get_post_meta(get_the_ID(), ‘price_key’, true);

}

?>
[/sourcecode]