CMB2 - how to add metabox to an existing options page (options page created also by new_cmb2_box)?

694 Views Asked by At

What do I want to accomplish ?

  1. Add new options-page with the use of new_cmb2_box -> this works OK

add_action( 'cmb2_admin_init', 'register_metabox' );

function register_metabox() {

    $cmb = new_cmb2_box( array(
        'id'           => 'testtesttest',
        'title'         => '_Ustawienia_Motywu_',
        'object_types' => array( 'options-page' ),
        'option_key'      => 'ustawienia_motywu',
        'parent_slug' => 'options-general.php'
    ) );

    }

  1. To just created options page (point 1 above) add one meta box, again, with the use of new_cmb2_box -> THIS PART DOES NOT WORK - how to make it work ? :

add_action( 'cmb2_admin_init', 'register_metabox2' );

function register_metabox2() {

    $cmb2 = new_cmb2_box( array(
        'id'           => 'test2',
        'title'         => 'title',
        'object_types' => array( 'options-page' ),
        'parent_slug' => 'options-general.php?page=ustawienia_motywu',
    ) );

    // Set our CMB2 fields

    $cmb2->add_field( array(
        'name' => __( 'Test Text', 'myprefix' ),
        'desc' => __( 'field description (optional)', 'myprefix' ),
        'id'   => 'test_text',
        'type' => 'text',
        // 'default' => 'Default Text',
    ) );

    $cmb2->add_field( array(
        'name'    => __( 'Test Color Picker', 'myprefix' ),
        'desc'    => __( 'field description (optional)', 'myprefix' ),
        'id'      => 'test_colorpicker',
        'type'    => 'colorpicker',
        'default' => '#bada55',
    ) );

}

How to make #2 work ? My guess is maby to use custom 'show_on_cb' ...

1

There are 1 best solutions below

0
corba On

You should put all to one function:

add_action( 'cmb2_admin_init', 'register_metabox' );
function register_metabox() {

    $cmb = new_cmb2_box( array(
        'id'            => 'testtesttest',
        'title'         => '_Ustawienia_Motywu_',
        'object_types'  => array( 'options-page' ),
        'option_key'    => 'ustawienia_motywu',
        'parent_slug'   => 'options-general.php'
    ) );

    $cmb->add_field( array(
        'name' => __( 'Test Text', 'myprefix' ),
        'desc' => __( 'field description (optional)', 'myprefix' ),
        'id'   => 'test_text',
        'type' => 'text',
    ) );

    $cmb->add_field( array(
        'name'    => __( 'Test Color Picker', 'myprefix' ),
        'desc'    => __( 'field description (optional)', 'myprefix' ),
        'id'      => 'test_colorpicker',
        'type'    => 'colorpicker',
        'default' => '#bada55',
    ) );
}