我想将一个自定义元框添加到特定的自定义元类型“chifres”,将两个自定义元框添加到特定的自定义元类型“presse”。这就是我取得的成绩:
这是我的代码:
//Add custom metadata
function add_custom_metadata_boxes() {
add_meta_box(
\'custom_meta_box\', // $id
\'Values\', // $title
\'show_custom_boxes\', // $callback
\'foo1\', //Custom post types
\'normal\', // $context
\'high\' // $priority
);
}
$prefix = \'custom_\';
$custom_meta_fields = array(
array(
\'name\' => \'number\',
\'label\' => \'Number\',
\'id\' => $prefix . \'number\',
\'type\' => \'number\',
\'std\' => \'\'
)
);
// The Callback for the first one
function show_custom_boxes() {
global $custom_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 ($custom_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\']) {
// checkbox
case \'number\':
echo \'<input type="number" min="0" step="1" pattern="\\d+" placeholder="Fill in a number" name="\', $field[\'id\'], \'" id="\', $field[\'id\'], \'" value="\', $meta ? $meta : $field[\'std\'], \'" size="30" style="width:97%" />\', \'<br />\', $field[\'desc\'];
break;
} //end switch
echo \'</td></tr>\';
} // end foreach
echo \'</table>\'; // end table
}
add_action(\'add_meta_boxes\', \'add_custom_metadata_boxes\');
function save_custom_meta($post_id) {
global $custom_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 (\'page\' == $_POST[\'post_type\']) {
if (!current_user_can(\'edit_page\', $post_id))
return $post_id;
} elseif (!current_user_can(\'edit_post\', $post_id)) {
return $post_id;
}
// loop through fields and save the data
foreach ($custom_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
}
add_action(\'save_post\', \'save_custom_meta\');
“chifres”框工作得很好,我只是不知道如何将其他自定义元框添加到另一个自定义帖子类型。
有什么建议吗?
SO网友:Brad Dalton
这个add_meta_box()
函数第四个参数是为后端添加CPT的位置。
$post_type
(string) (required) The type of Write screen on which to show the edit screen section (\'post\', \'page\', \'dashboard\', \'link\', \'attachment\' or \'custom_post_type\' where custom_post_type is the custom post type slug)
您应该能够使用第4个参数为多个CPT添加一个数组。
对于前端,您可以在自定义函数或模板文件中使用条件标记,具体取决于您想要输出的方式。
is_singular(\'your-cpt\')
或
is_post_type_archive(\'your-cpt\')