I am trying to display the label text of my CMB2 select not the value on the frontend. Currently my select field displays a list of a specific custom post type called fleet. When I add $gas = get_post_meta( get_the_ID(), 'gas__assign', true ); echo $gas; into the front of my website it is displaying the value which in this case is the post ID. Is there away I can display the selected option instead of the value?
Custom Select
$gas->add_field( array(
'name' => 'Assign',
'desc' => 'assign a vehicle',
'id' => $prefix . 'gas__assign',
'type' => 'select',
'options' => get_gas_options('fleettype'),
));
Select Field Selection of a CPT
function get_gas_options($a) {
$args = array(
'post_type' => 'fleet',
'orderby' => 'ID',
'post_status' => 'publish',
'order' => 'ASC',
'posts_per_page' => -1 // this will retrive all the post that is published
);
$result = new WP_Query( $args );
$title_list[''] = "Assign a Vehicle";
if ( $result-> have_posts() ) :
while ( $result->have_posts() ) : $result->the_post();
$title_list[get_the_ID()] = get_the_title();
endwhile;
endif;
wp_reset_postdata();
return $title_list;
}
I am trying to display the label text of my CMB2 select not the value on the frontend. Currently my select field displays a list of a specific custom post type called fleet. When I add $gas = get_post_meta( get_the_ID(), 'gas__assign', true ); echo $gas; into the front of my website it is displaying the value which in this case is the post ID. Is there away I can display the selected option instead of the value?
Custom Select
$gas->add_field( array(
'name' => 'Assign',
'desc' => 'assign a vehicle',
'id' => $prefix . 'gas__assign',
'type' => 'select',
'options' => get_gas_options('fleettype'),
));
Select Field Selection of a CPT
function get_gas_options($a) {
$args = array(
'post_type' => 'fleet',
'orderby' => 'ID',
'post_status' => 'publish',
'order' => 'ASC',
'posts_per_page' => -1 // this will retrive all the post that is published
);
$result = new WP_Query( $args );
$title_list[''] = "Assign a Vehicle";
if ( $result-> have_posts() ) :
while ( $result->have_posts() ) : $result->the_post();
$title_list[get_the_ID()] = get_the_title();
endwhile;
endif;
wp_reset_postdata();
return $title_list;
}
Share
Improve this question
edited Aug 27, 2020 at 14:42
bigant841
asked Aug 27, 2020 at 14:32
bigant841bigant841
17211 bronze badges
1 Answer
Reset to default 0I'm using the $gas
example variable from your question in my answer below. Sorry for the bad formatting, I'm typing this on my mobile device.
If you're certain that $gas
will always contain a post ID then the simplest solution is to just do echo ! empty($gas) ? get_the_title( $gas ) : '';
(Ternary operator used here)
Another way is to get the options in your template to a variable and access the resulting associative array with $gas
as the key to get the corresponding array value (label in this case).
$options = get_gas_options('fleettype'); echo $options[ $gas ] ?? '';
(null coalescing operator used here).