在 Wordpress 中使用 CMB2 添加带有自定义回调函数的自定义元框?

Add Custom Meta Box With a Custom Callback Function using CMB2 in Wordpress?

我正在使用 wordpress 开发一个项目,我正在使用 CMB2 插件来构建自定义元框和字段。但在某些情况下,我需要一个带有自定义回调函数的自定义元框,因此我将在其中创建一些自定义动态字段。

我从 c​​mb 得到的是添加一个带有自定义回调的元字段,比如

$cmb->add_field( array(
    'name'    => __( 'Test', 'cmb2' ),
    'id'      => $prefix . 'test',
    'type'    => 'text',
    'default' => 'prefix_set_test_default',
) );

回调:

function prefix_set_test_default( $field_args, $field ) {
    return my_custom_fields;

}

我现在可以做什么?

提前致谢

Below is proper way to add custom meta by CMB2 meta box.

add_action( 'cmb2_admin_init', 'cmb2_custom_metaboxes' );


function cmb2_sample_metaboxes() {

     //your custom prefix
     $prefix = '_customprefix_';

     $cmb = new_cmb2_box( array(
        'id'            => 'test_metabox',
        'title'         => __( 'Test Metabox', 'cmb2' ),
        'object_types'  => array( 'page', ), // Post type
        'context'       => 'normal',
        'priority'      => 'high',
        'show_names'    => true, // Show field names on the left
        // 'cmb_styles' => false, // false to disable the CMB stylesheet
        // 'closed'     => true, // Keep the metabox closed by default
    ) );

    // Regular text field
    $cmb->add_field( array(
        'name'       => __( 'Test', 'cmb2' ),
        'desc'       => __( 'field description', 'cmb2' ),
        'id'         => $prefix . 'text',
        'type'       => 'text',
         'default' => 'prefix_set_test_default',
    ) );

    //Add more field as custom meta
}

function prefix_set_test_default($field_args, $field){
     return my_custom_fields;
}

您必须 return 来自 CMB2 回调函数的关联数组才能生成您的自定义字段。

这是一个示例,说明如何 return 来自自定义 post 类型的 post 下拉列表:

$cmb->add_field( [
   'name'             => __( 'Posts dropdown', 'cmb2' ),
   'id'               => $prefix . 'dropdown',
   'type'             => 'select',
   'show_option_none' => true,
   'options_cb'       => 'get_my_custom_posts',
] );

回调函数

function get_my_custom_posts() {
   $posts = get_posts( [ 'post_type' => 'my_custom_post_type' ] );
   $options = [];

   foreach ( $posts as $post ) {
      $options[ $post->ID ] = $post->post_title;
   }

   return $options;
}