0

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;
}

               
         

1 Answer 1

0

I'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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.