Support » Plugin: CMB2 » pull options set on a select field.

  • Resolved Xavier Serrano

    (@xavierserranoa)


    Is there a way where I can call the options set on the add_field arguments. so that I can print those values somewhere else?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Michael Beckwith

    (@tw2113)

    The BenchPresser

    Hi @xavierserranoa

    We do have a cmb2_get_field( 'cmb_id', 'field_id' )->options() where you would want to pass in your ID parameter for the metabox, and then the ID parameter for the field that you’re wanting to fetch. HOWEVER this will only work if your using the cmb2_init hook to register, which may not be the case. If you’re using the cmb2_admin_init hook to register your stuff, then the function won’t find its data.

    Since we recommending using the cmb2_admin_init hook unless this is specifically for the frontend, we have the following as a better alternative.

    First define callback to provide the available options.

    function yourprefix_demo_select_options() {
    	return array(
    		'' => __( 'Nope', 'cmb2' ),
    		'standard' => __( 'Option One', 'cmb2' ),
    		'custom'   => __( 'Option Two', 'cmb2' ),
    		'none'     => __( 'Option Three', 'cmb2' ),
    	);
    }
    

    Then utilize that function when constructing the metabox.

    $cmb_demo->add_field( array(
    	'name' => __( 'Test Select', 'cmb2' ),
    	'desc' => __( 'field description (optional)', 'cmb2' ),
    	'id'   => '_yourprefix_demo_select',
    	'type' => 'select',
    	'options_cb' => 'yourprefix_demo_select_options',
    ) );
    

    This way you could use the same function elsewhere to get its data, but also pass them in to the dropdown.

    Plugin Author Justin Sternberg

    (@jtsternberg)

    Just wanted to jump in an clarify a tiny bit here.

    If you’re using the cmb2_admin_init hook to register your stuff, then the function won’t find its data.

    This is only true if you’re using it on the frontend. Basically, cmb2_get_field will only return fields that are registered, and when using the cmb2_admin_init hook (as we recommend for performance reasons), your fields would only be registered in wp-admin. So if your use-case is getting the options somewhere else in the admin, you’d be just fine (but also, that’s assuming your calling this _after_ the cmb2_admin_init hook is fired, not before).

    The yourprefix_demo_select_options function solution Michael provided is likely the safest bet for ultimate flexibility.

    this all helps a lot guys thanks!!!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘pull options set on a select field.’ is closed to new replies.