Custom field (get_post_meta) issue
-
Hi,
I’m having trouble to display the value of a custom select field in frontend of my website.
1) I have added this custom select field in backend:
woocommerce_wp_select( array( 'id' => 'myfieldname', 'label' => __( 'My Select Field', 'woocommerce' ), 'options' => array( 'one' => __( 'Option 1', 'woocommerce' ), 'two' => __( 'Option 2', 'woocommerce' ), 'three' => __( 'Option 3', 'woocommerce' ) ) ) );
2) I save value like this:
update_post_meta( $post_id, 'myfieldname', esc_attr( $_POST['myfieldname'] ) );
3) Display it on frontend:
echo get_post_meta(get_the_ID(), 'myfieldname', true );
BUT, after I select for example ‘option 2’ in backend, this is displayed in frontend like this: ‘two’
So part ‘Option 2’ is not displayed. Guess something’s wrong with code of step 3?
Guido
-
There’s not really anything wrong, you’re just a bit confused about what’s going on. I’m not familiar with the woo select function, but based on your described results, I’m certain it outputs
<option>
lines which, for the ‘two’ option, would look like this:
<option value="two">Option 2</option>
Thus when this option is selected, the value in
$_POST['myfieldname']
would naturally be “two”, so your script 2 will store it as such and your script 3 displays it.You have several options on how to end up displaying ‘Option 2’. Write your own select/option HTML output where the values are set correctly. Change the array key names passed to the woo select function. In either script 2 or 3 use an array like the woo options argument to translate ‘two’ back to ‘Option 2’. Instead of a translation array, you could hard code a PHP switch/case structure to do the same thing.
One choice is probably more efficient than the others, I’m not sure which. I would suggest the write your own option unless there’s a reason I’m unaware of to use one of the others.
Hi,
Thanks for your response!
I did not thought about the possibility this is a woocommerce issue > so it might handle the select box different from default WP select box in frontend.I will work on this.
Guido
@bcworkz: I decided to open a topic in Woocommerce forum because I have no idea how to solve this…
https://wordpress.org/support/topic/get_post_meta-get-value-of-selectbox?
Guido
@bcworkz: Yes, I have solved it:
https://wordpress.org/support/topic/get_post_meta-get-value-of-selectbox?Guido
Nice work! Thanks for reporting back.
- The topic ‘Custom field (get_post_meta) issue’ is closed to new replies.