Search
Close this search box.

WordPress: Custom Metabox for custom post type

Amitpal Singh
Amitpal Singh
April 21, 2023

How to use custom metabox in wordpress for post types?

//change post type for the first time here

function lets_add_custom_meta_box()
{
    add_meta_box("my-custom-meta-box", "Additional Info", "my_custom_meta_box_markup", "post", "side", "high", null);
}

add_action("add_meta_boxes", "lets_add_custom_meta_box");


function my_custom_meta_box_markup($object)
{
    wp_nonce_field(basename(__FILE__), "meta-box-nonce");
    ?>
        <div>
			
			<input type="hidden" class="backend-post-id" value="<?php echo $object->ID;  ?>">
			
			<div class="price">
				<label for="meta-box-subtitle" style="min-width:125px;display:inline-block;">Subtitle</label>
				<input name="meta-box-subtitle" class="subtitle-value" type="text" value="<?php echo get_post_meta($object->ID, "meta-box-subtitle", true); ?>">
				<br><br>
			</div>
			
			

        </div>
    <?php  
}


function save_my_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;

//change post type second time here
    $slug = "post";
    if($slug != $post->post_type)
        return $post_id;

    $meta_box_subtitle = "";

    if(isset($_POST["meta-box-subtitle"]))
    {
        $meta_box_subtitle = $_POST["meta-box-subtitle"];
    }   
    update_post_meta($post_id, "meta-box-subtitle", $meta_box_subtitle);

}

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

Share this post:

How to Attribute?

Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
for Example: Website, Social Media, Blogs, ebooks , newsletter, etc.
Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
Copied!

Got a Question? Check out our FAQ Section.

Your action, our appreciation

It encourage us to give you more valuable content on website.