首页 > 解决方案 > 如何在“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' );

谢谢

标签: phpwordpress

解决方案


推荐阅读