TransWikia.com

A better way to add a meta box to custom post types

WordPress Development Asked by yevg on November 17, 2021

Id like to customize the UI for adding and editing a custom post type such that each custom field is included as a separate input field on the "new post" and "edit post" forms (as opposed to having to select them from the Custom Fields dropdown menu, as is the default).

Having looked around it appears that what Im looking for in known as a meta_box and the function to add one is add_meta_box().

I found this tutorial which goes through the process of adding a custom post type and then a meta box – basically what I’m trying to do, but the code kinda sucks..

<?php

add_action("admin_init", "admin_init");
add_action('save_post', 'save_price');

function admin_init(){
    add_meta_box("prodInfo-meta", "Product Options", "meta_options", "product", "side", "low");
}

function meta_options(){
    
    global $post;
    $custom = get_post_custom($post->ID);
    $price = $custom["price"][0];
?>
    
    <label>Price:</label><input name="price" value="<?php echo $price; ?>" />

<?php
}

function save_price(){
    global $post;
    update_post_meta($post->ID, "price", $_POST["price"]);
}

?>

First of all, this guy is using the same name for one of the functions as the name of the hook admin_init – why would you do that??

Then I see the admin-init function calls add_meta_box() ..ok so far so good. But then add_meta_box() takes the meta_options function as one of the parameters and it looks like that function is what actually generates the input box by manually echoing the input field html. Then save_price manually appends the data from this field to the list of fields on submit.

Do I really have to go through this process for every single custom field on every single post type?

I feel like its not too much to ask to create a custom post type and have the ability to simply pass an array or something with custom field data and have those fields simply populate on the add and edit pages. Is that not possible? There’s got to be a simpler and more scalable way to create a "meta_box", right?

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP