虽然您应该添加一些验证,但对于当前版本的WordPress,此操作似乎并不复杂。
基本上,向自定义帖子类型添加自定义字段需要两个步骤:
创建一个包含自定义字段的元框,将自定义字段保存到数据库中。以下是这些步骤的总体描述:http://wordpress.org/support/topic/is-it-possible-to-add-an-extra-field-to-a-custom-post-type
示例:
将名为“function”的自定义字段添加到名为“prefix teammembers”的自定义帖子类型中。
首先添加元盒:
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\' );
如果您添加或编辑“prefix teammembers”,则
add_meta_boxes_{custom_post_type}
挂钩已触发。看见
http://codex.wordpress.org/Function_Reference/add_meta_box 对于
add_meta_box()
作用在上述调用中
add_meta_box()
是
prefix_teammembers_metaboxes_html
, 用于添加表单字段的回调:
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
}
在第二步中,将自定义字段添加到数据库中。保存时
save_post_{custom_post_type}
挂钩已触发(自3.7版起,请参阅:
https://stackoverflow.com/questions/5151409/wordpress-save-post-action-for-custom-posts). 您可以挂接此链接以保存自定义字段:
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\' );