WordPress Add_meta_box to Custom Post Type |
X

Congrats, You are Subscribed to Receive Updates.

WordPress Add_meta_box to Custom Post Type


Introduction

From WordPress Admin Post edit page, we may need to input some custom form inputs as like price and size metrics for woocommerce Plugin. WordPress Add_meta_box to Custom Post Type. For many custom fields we need to add extra fields to a post  or a page. So, here I am giving a sample code to add a meta-box with custom fields and save it .

And also you can have the edit option with it. First of all we have to add a meta box to a post or page. You can add it to a custom post type too. Here is very simple and lite weight solution to make it happen.

function kv_textbox_metaboxes( ) {
   global $wp_meta_boxes;
   add_meta_box('postfunctiondiv', __('Sample TextBox'), 'kv_textbox_metaboxes_html', 'kv_textbox', 'normal', 'high');
}
add_action( 'add_meta_boxes_post_type', 'kv_textbox_metaboxes' ); // Yuo have to replace "post_type" with your custom post type

The above code will create a custom metabox on your custom post type. Now we need to add the form component to work on it. The following code helps you to add a input type text .wp_kv_functions

function kv_textbox_metaboxes_html(){
    global $post;
    $custom = get_post_custom($post->ID);
    $kv_textbox = isset($custom["kv_textbox"][0])?$custom["kv_textbox"][0]:'';
?>
    <label>Example TextBox:</label><input name="kv_textbox" value="<?php echo $kv_textbox; ?>">
<?php
}

Than, now we need to save and get the option . This function is common for Add new and edit.

function kv_textbox_save_post(){
    if(empty($_POST)) return; 
    global $post;
    update_post_meta($post->ID, "kv_textbox", $_POST["kv_textbox"]);
}   

add_action( 'save_post_post_type', 'kv_textbox_save_post' );

Thats it. now , you can see a sample meta box on your custom post type’s Add new page.

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, PHP and Data Analyst. Database Management Advance Level

Comment Below

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

*

Current ye@r *

Menu

Sidebar