Skip to content

Instantly share code, notes, and snippets.

@mustardBees
Last active June 8, 2022 09:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mustardBees/f970b89dc45876524c8e to your computer and use it in GitHub Desktop.
Save mustardBees/f970b89dc45876524c8e 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_post_options',
'wp_query_args' => array(
'post_type' => 'page',
),
) );
/**
* Get a list of posts.
*
* Generic function to return an array of posts formatted for CMB2. Simply pass
* in your WP_Query 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_post_options',
* 'wp_query_args' => array(
* 'post_type' => 'page',
* ),
* ) );
*
* @param CMB2_Field $field The field object.
*
* @return array An array of options that matches the CMB2 options array.
*/
function iweb_get_cmb2_post_options( $field ) {
$defaults = array(
'posts_per_page' => -1,
'no_found_rows' => true,
'cache_results' => false,
'orderby' => 'menu_order title',
'order' => 'ASC',
);
$args = $field->args( 'wp_query_args' );
$args = is_array( $args ) ? $args : array();
$args = array_replace_recursive( $defaults, $args );
$posts = new WP_Query( $args );
$post_options = array();
if ( $posts->have_posts() ) {
$posts_with_hierarchy = iweb_build_post_tree( $posts->posts );
$post_options = wp_list_pluck( $posts_with_hierarchy, 'post_title', 'ID' );
}
return $post_options;
}
/**
* Sort posts into a tree structure to show post hierarchy.
*
* In order to show hierarchical posts, we recursively build an options array,
* prepending the post title with a depth indicator to give the post some
* context.
*
* @param array $posts Array containing WP_Post objects.
* @param int $parent_id The current parent.
* @param int $level The current level.
*
* @return array
*/
function iweb_build_post_tree( $posts, $parent_id = 0, $level = 0 ) {
$branch = array();
foreach ( $posts as $post ) {
if ( $parent_id == $post->post_parent ) {
$post->post_title = str_repeat( '&mdash; ', $level ) . $post->post_title;
$branch[] = $post;
$children = iweb_build_post_tree( $posts, $post->ID, $level + 1 );
if ( ! empty( $children ) ) {
foreach ( $children as $child ) {
$branch[] = $child;
}
}
}
}
return $branch;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment