我正在尝试在WordPress中实现自定义字段。
我所苦恼的是您不能在Step2中全局使用数组。
由于我不想在Step4中重新定义相同的数组,因此我想重用Step2和Step4中在Step1中定义的数组。
如何在step2中使用step1的数组?
// Step1.Array for using custom fields
$cf_media = array(
'cf_apple' => 'apple',
'cf_banana' => 'banana',
);
$cf_service = array(
'cf_apple' => 'apple',
'cf_melon' => 'melon',
);
// Step2.Set custom field
function adding_custom_meta_boxes($post_type, $post) {
switch ($post_type) {
case 'media':
global $cf_media; // I want to use an array globally here
add_meta_box( 'meta_info', 'media area', 'create_cf', 'media', 'normal', 'high', $cf_media );
break;
case 'service':
global $cf_service; // I want to use an array globally here
add_meta_box( 'meta_info', 'service area', 'create_cf', 'service', 'normal', 'high', $cf_service );
break;
default:
break;
}
}
add_action('add_meta_boxes', 'adding_custom_meta_boxes', 10, 2);
// Step3. Display of input area
function create_cf($post, $box) {
foreach( $box['args'] as $keyname=>$k ) {
$get_value = esc_html( get_post_meta( $post->ID, $keyname, true ) );
wp_nonce_field( 'action-' . $keyname, 'nonce-' . $keyname );
echo '<label for="' . $keyname . '">' . $k . '</label><br>';
echo '<input name="' . $keyname . '" value="' . $get_value . '" style="width: 100%;">';
}
}
/// Step4. Process to save custom field
function save_meta_field( $post_id ) {
// I hate that I have to define the same array again at this time.
// Here I want to reuse the previously defined array.
$cf_all = [
cf_apple, cf_namama, cf_melon
];
// For example : $cf_all = array_unique(array_marge($cf_media, $cf_service));
foreach( $cf_all as $d ) {
if ( isset( $_POST['nonce-' . $d] ) && $_POST['nonce-' . $d] ) {
if( check_admin_referer( 'action-' . $d, 'nonce-' . $d ) ) {
if( isset( $_POST[$d] ) && $_POST[$d] ) {
update_post_meta( $post_id, $d, $_POST[$d] );
}else{
update_post_meta( $post_id, $d, '' );
}
}
}
}
}
add_action( 'save_post', 'save_meta_field' );
谢谢