post元数据可以将多个值存储为postmeta
表,或作为值为序列化PHP数组的一个条目。序列化可能需要更少的代码,但不同的条目允许以后更快的查询(“给我所有至少选中了multicheck选项A的帖子”)。
我拿走了the code you linked to 并进行了以下更改以允许“多重检查”:
// in show():
// Line 254: replace it by:
$meta = get_post_meta($post->ID, $field[\'id\'], \'multicheck\' != $field[\'type\'] /* If multicheck this can be multiple values */);
// Add the following to the switch:
case \'multicheck\':
foreach ( $field[\'options\'] as $value => $name ) {
// Append `[]` to the name to get multiple values
// Use in_array() to check whether the current option should be checked
echo \'<input type="checkbox" name="\', $field[\'id\'], \'[]" id="\', $field[\'id\'], \'" value="\', $value, \'"\', in_array( $value, $meta ) ? \' checked="checked"\' : \'\', \' /> \', $name, \'<br/>\';
}
break;
// In save():
// Line 358: replace it by:
$old = get_post_meta($post_id, $name, \'multicheck\' != $field[\'type\'] /* If multicheck this can be multiple values */);
// Lines 409-413: Wrap them in an else-clause, and prepend them by:
if ( \'multicheck\' == $field[\'type\'] ) {
// Do the saving in two steps: first get everything we don\'t have yet
// Then get everything we should not have anymore
if ( empty( $new ) ) {
$new = array();
}
$aNewToAdd = array_diff( $new, $old );
$aOldToDelete = array_diff( $old, $new );
foreach ( $aNewToAdd as $newToAdd ) {
add_post_meta( $post_id, $name, $newToAdd, false );
}
foreach ( $aOldToDelete as $oldToDelete ) {
delete_post_meta( $post_id, $name, $oldToDelete );
}
} else {
// The original lines 409-413
}
两个额外的更改可防止在以下情况下出现PHP警告:
WP_DEBUG
已启用:
// Line 337:
if ( ! isset( $_POST[\'wp_meta_box_nonce\'] ) || !wp_verify_nonce($_POST[\'wp_meta_box_nonce\'], basename(__FILE__))) {
// Line 359:
$new = isset( $_POST[$field[\'id\']] ) ? $_POST[$field[\'id\']] : null;
通过这些更改,您可以通过如下定义来使用“multicheck”:
array(
\'name\' => \'Multicheck\',
\'id\' => $prefix . \'multicheck\',
\'type\' => \'multicheck\',
\'options\' => array(
\'a\' => \'Apple\',
\'b\' => \'Banana\',
\'c\' => \'Cherry\',
),
)