php - 如何在“add_meta_boxes”中使用全局函数?
问题描述
我正在尝试在 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' );
谢谢
解决方案
推荐阅读
- python - 在 Seaborn 中制作两个相邻的 BoxPlot
- python - Python itertools.product() 实现的解释?
- ubuntu-16.04 - 带有拆分隧道 VPN 的 kodi
- perf - perf.data 太大,事件太少
- python-3.x - 在图像上执行对象检测后如何打印检测到的类?
- python - 我如何从本网站获取这些信息?
- android - 如何在不使用 R8 混淆的情况下在 Android 中进行优化
- google-cloud-platform - 谷歌搜索控制台 API 返回 404
- spring - 如何在 Spring WebService / Spring WS Security 应用程序中禁用 CSRF 检查?
- django - django 模板中的多个散景图表