听起来您希望能够从核心WordPress自定义字段元框中输入这些值:
要做到这一点,我将使用自定义格式,然后在保存帖子时进行转换。
// This function converts "Accounting,Peter|Finance,Ben|Marketing,Joe" format
// to array("Accounting"=>"Peter", "Finance"=>"Ben", "Marketing"=>"Joe");
function smyles_convert_custom_format_to_array( $val ){
$employee_data = array();
// Create array with | as separator
$parts = explode( \'|\', $val );
if( ! empty( $parts ) ){
// Loop through each one
foreach( $parts as $part ){
// Split again based on comma
$part_array = explode( \',\', $part );
// As long as there is a value, let\'s add it to our employee array
if( ! empty( $part_array[0] ) && ! empty( $part_array[1] ) ){
// First value in array will be our key, second will be the value
$employee_data[ $part_array[0] ] = $part_array[1];
}
}
}
return $employee_data;
}
然后,您需要添加一个操作以在使用上述函数转换自定义格式后更新元数据:
// Add a custom action on save post so we can convert our custom format
add_action( \'save_post\', \'smyles_save_post_format_custom_field\', 99, 3 );
// This function will update the post meta with an array instead of using our custom format
function smyles_save_post_format_custom_field( $id, $post, $update ){
$custom_field = \'employees\';
// Change `post` below to something else if using custom post type
if( $post->post_type != \'post\' ) {
return;
}
// Only try to process if a value exists
if( ! empty( $_POST[ $custom_field ] ) ){
$value = smyles_convert_custom_format_to_array( $_POST[ $custom_field ] );
} else {
// Otherwise set $value to empty value, meaning custom field was deleted or has an empty value
$value = array();
}
update_post_meta( $id, $custom_field, $value, true );
}
如果要提取这些值,只需使用以下命令:
// Arrays are stored serialized, so let\'s get that first
$value = get_post_meta( $post_id, \'employees\', true);
瞧!利润