Last active
September 10, 2021 16:43
-
-
Save hirozed/115190c813cce4b2e460d027cac4b291 to your computer and use it in GitHub Desktop.
WordPress CMB2 Terms as Options
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$cmb2->add_field( | |
array( | |
'id' => '_[id]', | |
'name' => '', | |
'type' => '', | |
'options_cb' => __NAMESPACE__ . '\\get_term_options', | |
'get_term_args' => array( | |
'taxonomy' => '', | |
'hide_empty' => false, | |
), | |
) | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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