Skip to content

Instantly share code, notes, and snippets.

@mustardBees
Last active June 8, 2022 09:12
Show Gist options
  • Save mustardBees/9eb84e47e8afce5ecad2 to your computer and use it in GitHub Desktop.
Save mustardBees/9eb84e47e8afce5ecad2 to your computer and use it in GitHub Desktop.
<?php
// Example meta box field
$cmb->add_field( array(
'name' => 'Test Select',
'id' => 'test_select',
'type' => 'pw_multiselect',
'options_cb' => 'iweb_get_cmb2_term_options',
'get_terms_args' => array(
'taxonomy' => 'post_tag',
),
) );
/**
* Get a list of terms.
*
* Generic function to return an array of taxonomy terms formatted for CMB2.
* Simply pass in your get_terms arguments and get back a beautifully formatted
* CMB2 options array.
*
* Usage:
*
* $cmb->add_field( array(
* 'name' => 'Test Select',
* 'id' => $prefix . 'test_select',
* 'type' => 'select',
* 'options_cb' => 'iweb_get_cmb2_term_options',
* 'get_terms_args' => array(
* 'taxonomy' => 'post_tag',
* ),
* ) );
*
* @param CMB2_Field $field The field object.
*
* @return array An array of options that matches the CMB2 options array.
*/
function iweb_get_cmb2_term_options( $field ) {
$defaults = array(
'taxonomy' => 'category',
'hide_empty' => false,
);
$args = $field->args( 'get_terms_args' );
$args = is_array( $args ) ? $args : array();
$args = wp_parse_args( $args, $defaults );
$terms = get_terms( $args );
$term_options = array();
if ( ! empty( $terms ) ) {
$terms_with_hierarchy = iweb_build_term_tree( $terms );
$term_options = wp_list_pluck( $terms_with_hierarchy, 'name', 'term_id' );
}
return $term_options;
}
/**
* Sort terms into a tree structure to show term hierarchy.
*
* In order to show hierarchical terms, we recursively build an options array,
* prepending the term title with a depth indicator to give the term some
* context.
*
* @param array $terms Array containing WP_Term objects.
* @param int $parent_id The current parent.
* @param int $level The current level.
*
* @return array
*/
function iweb_build_term_tree( $terms, $parent_id = 0, $level = 0 ) {
$branch = array();
foreach ( $terms as $term ) {
if ( $parent_id == $term->parent ) {
$term->name = str_repeat( '&mdash; ', $level ) . $term->name;
$branch[] = $term;
$children = iweb_build_term_tree( $terms, $term->term_id, $level + 1 );
if ( ! empty( $children ) ) {
foreach ( $children as $child ) {
$branch[] = $child;
}
}
}
}
return $branch;
}
@eb-ai4
Copy link

eb-ai4 commented Jun 8, 2022

I think it would be better to use a callback as mentioned here https://cmb2.io/docs/field-parameters#-options_cb

This would prevent the function to fire at every page load.

@mustardBees
Copy link
Author

@eb-ai4 You're right. I've updated the gist with a later version of this helper function. This version also better represents hierarchical taxonomies.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment