This plugin gives you two additional field types based on Select2:
pw_select
field acts much like the default select
field. However, it adds typeahead-style search allowing you to quickly make a selection from a large listpw_multiselect
field allows you to select multiple values with typeahead-style search. The values can be dragged and dropped to reorderYou can install this field type as you would a WordPress plugin:
/wp-content/plugins/
directoryAlternatively, you can include this field type within your plugin/theme. The path to front end assets (JS/CSS) can be filtered using pw_cmb2_field_select2_asset_path
. See an example where we load assets from the current active theme.
pw_select
- Select box with with typeahead-style search. Example:
$cmb->add_field( array(
'name' => 'Cooking time',
'id' => $prefix . 'cooking_time',
'desc' => 'Cooking time',
'type' => 'pw_select',
'options' => array(
'5' => '5 minutes',
'10' => '10 minutes',
'30' => 'Half an hour',
'60' => '1 hour',
),
) );
pw_multiselect
- Multi-value select box with drag and drop reordering. Example:
$cmb->add_field( array(
'name' => 'Ingredients',
'id' => $prefix . 'ingredients',
'desc' => 'Select ingredients. Drag to reorder.',
'type' => 'pw_multiselect',
'options' => array(
'flour' => 'Flour',
'salt' => 'Salt',
'eggs' => 'Eggs',
'milk' => 'Milk',
'butter' => 'Butter',
),
) );
You can specify placeholder text through the attributes array. Example:
$cmb->add_field( array(
'name' => 'Ingredients',
'id' => $prefix . 'ingredients',
'desc' => 'Select this recipes ingredients.',
'type' => 'pw_multiselect',
'options' => array(
'flour' => 'Flour',
'salt' => 'Salt',
'eggs' => 'Eggs',
'milk' => 'Milk',
'butter' => 'Butter',
),
'attributes' => array(
'placeholder' => 'Select ingredients. Drag to reorder'
),
) );
You can define Select2 configuration options using HTML5 data-*
attributes. It's worth reading up on the available options over on the Select2 website. Example:
$cmb->add_field( array(
'name' => 'Ingredients',
'id' => $prefix . 'ingredients',
'desc' => 'Select ingredients. Drag to reorder.',
'type' => 'pw_multiselect',
'options' => array(
'flour' => 'Flour',
'salt' => 'Salt',
'eggs' => 'Eggs',
'milk' => 'Milk',
'butter' => 'Butter',
),
'attributes' => array(
'data-maximum-selection-length' => '2',
),
) );
You may want to populate the options array dynamically. Common use cases include listing out posts and taxonomy terms. I've written a number of generic helper functions which can be used to return a CMB2 style array for both posts and terms.
If you’d like to help out, pull requests are more than welcome!