I got your “broken” code in your answer to work and will explain why. First, here’s the edited code that wasn’t working for you:
<?php
//Get your post ID with a variable
$this_post_id = get_the_ID();
//Removed get function from get_post_meta to make functionality clearer
//I tend to avoid nesting functions that are grabbing post information for easier debugging/reading
//You need to use the field ID as the parameter in get_post_meta, what you had was the meta box id, not the field itself
//Therefore WordPress didn't know what to retrieve since the metabox itself wasn't the custom meta you were grabbing
$key_2_value = get_post_meta( $this_post_id, 'custom_select', true );
//Debugging got you an empty string before, uncomment this to see the results now
//var_dump($key_2_value);
if( ! empty( $key_2_value )) {
//This works now - yay!
echo $key_2_value;
} ?>
The first thing I did was avoid nesting functions within functions so I made get_the_ID
into a variable as well. It makes for easier reading and debugging should anything happen because then you can run var_dump
on your variables piece by piece to confirm you’re getting all the information you need when troubleshooting.
Running var_dump on $key_2_value
gave me an empty string. I ran var_dump on $this_post_id
which was working for the post ID, cool, then I realized something.
I changed this:
get_post_meta( get_the_ID(), 'custom_meta_box', true );
To this:
get_post_meta( $this_post_id, 'custom_select', true );
If you look at your functions file, in your $custom_meta_fields
definition, you gave the select box an ID of “custom_select”:
$prefix = 'custom_';
$custom_meta_fields = array(
array(
'label'=> 'Map Icon',
'desc' => 'A description for the field.',
'id' => $prefix.'select', //right here!
'type' => 'select',
'options' => array (
'one' => array (
'label' => 'Option One',
'value' => 'three'
),
'two' => array (
'label' => 'Option Two',
'value' => 'two'
),
'three' => array (
'label' => 'Option Three',
'value' => 'three'
)
)
)
);
So with get_post_meta, the $key
parameter is the ID of the post meta field. And so you had the name of your meta box, custom_meta_box
there instead of the name of the actual field itself. Once I changed that to custom_select, it worked.
Hope that helped! 🙂