Skip to content

Instantly share code, notes, and snippets.

@crossreftech
Created April 13, 2015 07:22
Show Gist options
  • Save crossreftech/bf8c734c8de52602a981 to your computer and use it in GitHub Desktop.
Save crossreftech/bf8c734c8de52602a981 to your computer and use it in GitHub Desktop.
<?php
// I hope this can help out someone else so they don't go though the same frustration that I did. I was trying to use the taxonomy_select
// metabox to display two dropdowns/select boxes but couldn't get them both to save. Saving or updating would force both to save as the
// second value. Below is the code that I used to allow me to save the data separately into usable post meta. If you are using this with
// multiple selects there is still no need to create more then one function, this will work on all of them.
// I first created a function outside the metabox to loop though my custom taxonomy.
function get_team_names( $taxonomy = 'team_category', $args = array() ) {
$terms = get_terms('team_category', 'orderby=none&hide_empty');
// Initate an empty array
$term_options = array();
if ( ! empty( $terms ) ) {
foreach ( $terms as $term ) {
$term_options[ $term->term_id ] = $term->name;
}
}
return $term_options;
}
add_action( 'cmb2_init', 'sports_ticker_custom_metaboxes' );
// Then when created the metaboxes I then pulled it into my metabox like this. This allows you to pull in a list of your taxonomies
// very much like the taxonomy_select metabox but will save all values separately.
$ticker_data->add_field( array(
'name' => 'Home Team',
'desc' => 'Choose the home team.',
'id' => $prefix . 'ticker_home_team',
'type' => 'select',
'options' => get_team_names(),
) );
// Lastly, below is the code needed to display the information on the front end.
global $post;
$home_team_select = get_post_meta( $post->ID, '_ticker_data_ticker_home_team', true );
$away_team_select = get_post_meta( $post->ID, '_ticker_data_ticker_away_team', true );
$home_name = get_term_by('id', $home_team_select, 'team_category');
$homeTeam = $home_name->slug;
$away_name = get_term_by('id', $away_team_select, 'team_category');
$awayTeam = $away_name->slug;
echo $homeTeam . ' vs ' . $awayTeam;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment