Wordpress - How to Add Custom Fields to a Custom Post Type?

Add/edit the supports argument ( while using register_post_type ) to include the custom-fields to post edit screen of you custom post type:

'supports' => array( 
  'title', 
  'editor', 
  'excerpt', 
  'thumbnail', 
  'custom-fields', 
  'revisions' 
)

Source: https://codex.wordpress.org/Using_Custom_Fields#Displaying_Custom_Fields


This is probably more complicated than you think, I would look into using a framework:

  • http://wpgear.org/#meta-fields

If you want to write your own , here are some decent tutorials:

  • http://net.tutsplus.com/tutorials/wordpress/creating-custom-fields-for-attachments-in-wordpress/
  • http://sltaylor.co.uk/blog/control-your-own-wordpress-custom-fields/
  • http://thinkvitamin.com/code/create-your-first-wordpress-custom-post-type/

Although you should have to add some validation, this action does not seem to be complicated for the current version of WordPress.

Basically you need two steps to add a Custom Field to a Custom Post Type:

  1. Create a metabox which holds your Custom Field
  2. Save your Custom Field to the database

These steps are globally described here: http://wordpress.org/support/topic/is-it-possible-to-add-an-extra-field-to-a-custom-post-type

Example:

Add a Custom Field called "function" to a Custom Post Type called "prefix-teammembers".

First add the metabox:

function prefix_teammembers_metaboxes( ) {
   global $wp_meta_boxes;
   add_meta_box('postfunctiondiv', __('Function'), 'prefix_teammembers_metaboxes_html', 'prefix_teammembers', 'normal', 'high');
}
add_action( 'add_meta_boxes_prefix-teammembers', 'prefix_teammembers_metaboxes' );

If your add or edit a "prefix-teammembers" the add_meta_boxes_{custom_post_type} hook is triggered. See http://codex.wordpress.org/Function_Reference/add_meta_box for the add_meta_box() function. In the above call of add_meta_box() is prefix_teammembers_metaboxes_html, a callback to add your form field:

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

In the second step you have your custom field to the database. On saving the save_post_{custom_post_type} hook is triggered (since v 3.7, see: https://stackoverflow.com/questions/5151409/wordpress-save-post-action-for-custom-posts). You can hook this to save your custom field:

function prefix_teammembers_save_post()
{
    if(empty($_POST)) return; //why is prefix_teammembers_save_post triggered by add new? 
    global $post;
    update_post_meta($post->ID, "function", $_POST["function"]);
}   

add_action( 'save_post_prefix-teammembers', 'prefix_teammembers_save_post' );