Skip to content

Instantly share code, notes, and snippets.

@hirozed
Last active September 10, 2021 16:43
Show Gist options
  • Save hirozed/115190c813cce4b2e460d027cac4b291 to your computer and use it in GitHub Desktop.
Save hirozed/115190c813cce4b2e460d027cac4b291 to your computer and use it in GitHub Desktop.
WordPress CMB2 Terms as Options
<?php
$cmb2->add_field(
array(
'id' => '_[id]',
'name' => '',
'type' => '',
'options_cb' => __NAMESPACE__ . '\\get_term_options',
'get_term_args' => array(
'taxonomy' => '',
'hide_empty' => false,
),
)
);
<?php
/**
* Gets a number of terms and displays them as options.
*
* @param CMB2_Field $field The CMB2 field.
* @return array An array of options that matches the CMB2 options array.
*/
function get_term_options( $field ) {
$args = $field->args( 'get_term_args' );
if ( empty( $args ) ) {
return;
}
$terms = get_terms( $args );
$term_return = array();
if ( ! empty( $terms ) ) {
foreach ( $terms as $term ) {
$term_return[ $term->term_id ] = $term->name;
}
}
return $term_return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment