这是我用来在自定义帖子类型中添加自定义字段的代码示例。或者您可以使用插件高级自定义字段添加自定义字段并将它们附加到您的自定义帖子类型。
我希望这可以帮助你!
<?php
// Metabox declaration
$prefix = 'bookmark_';
// The only way I found too pass the fields informations to the action
global $bookmark_meta_fields;
$bookmark_meta_fields = array(
array(
'label'=> 'Url',
'desc' => 'Url of the bookmark.',
'id' => $prefix.'url',
'type' => 'text'
),
array(
'label'=> 'Comments',
'desc' => 'A small comments about the bookmarks.',
'id' => $prefix.'comment',
'type' => 'textarea'
),
);
add_action('add_meta_boxes', 'vban_bookmark_metabox');
function vban_bookmark_metabox() {
add_meta_box(
'bookmark_info', // $id
'Bookmark info', // $title
'vban_bookmark_metabox_show', // $callback
'vbanBookmarks', // $page
'normal', // $context
'high'); // $priority
}
/*
* show metabox function
*/
function vban_bookmark_metabox_show() {
global $bookmark_meta_fields, $post;
// Use nonce for verification
echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
// Begin the field table and loop
echo '<table class="form-table">';
foreach ($bookmark_meta_fields as $field) {
// get value of this field if it exists for this post
$meta = get_post_meta($post->ID, $field['id'], true);
// begin a table row with
echo '<tr>
<th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
<td>';
switch($field['type']) {
case 'text':
echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="30" />
<br /><span class="description">'.$field['desc'].'</span>';
// textarea
break;
case 'textarea':
echo '<textarea name="'.$field['id'].'" id="'.$field['id'].'" cols="60" rows="4">'.$meta.'</textarea>
<br /><span class="description">'.$field['desc'].'</span>';
break;
} //end switch
echo '</td></tr>';
} // end foreach
echo '</table>'; // end table
}
/*
* SAVE metabox custom_field
*/
add_action('save_post', 'vban_bookmark_metabox_save');
// Save the Data
function vban_bookmark_metabox_save($post_id) {
global $bookmark_meta_fields;
// verify nonce
if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) {
return $post_id;
}
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
return $post_id;
}
// check permissions
if ('vbanBookmarks' == $_POST['post_type']) {
if (!current_user_can('edit_bookmark', $post_id))
return $post_id;
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
// loop through fields and save the data
foreach ($bookmark_meta_fields as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
} // end foreach
}
?>