[Question] - Date picker. Stuck. How to render an output?
Version
- Carbon Fields: 2.2.0
- WordPress: 4.9.7
- PHP: 7.1
Expected Behavior
Echo output of the date in d-m-Y.
Although what I really want is to echo only the Y part.
Actual Behavior
Empty output. I know my code is wrong!
Also not sure if I've done set_storage and set_input_format correctly?
Container definition
Field::make( 'date', 'crb_event_start', 'Event Start' ),
// ->set_storage_format( 'd-m-Y' ),
// ->set_input_format( 'd-m-Y', 'd-m-Y' ),
<?php echo carbon_get_the_post_meta( 'crb_event_start' ); ?>
I figure it out. Basic example for the documentation.
<?php
$date = carbon_get_the_post_meta( 'crb_event_start' );
echo date( 'd-m-Y' );
?>
Hi @breath-ee,
The code from your first comment should work fine. The ->set_storage_format( 'd-m-Y' ) will save the date in d-m-Y into the database and then you can show it on the front end with the <?php echo carbon_get_the_post_meta( 'crb_event_start' ); ?>
Also, if you want to echo only the Y part you can use the date() function
$date = carbon_get_the_post_meta( 'crb_event_start' );
echo date( 'Y', strtotime( $date ) );
Regarding the following code from your second comment:
<?php
$date = carbon_get_the_post_meta( 'crb_event_start' );
echo date( 'd-m-Y' );
?>
The echo date( 'd-m-Y' ); part will print the current date and it has nothing in common with the crb_event_start date.
If you have more questions, I will be happy to help.
@deqngeorgiev, thanks for the reply. 👍
So I changed the code output back to <?php echo carbon_get_the_post_meta( 'crb_event_start' ); ?> and added back ->set_storage_format( 'd-m-Y' ), now I'm getting an output of 01-07-2018 which is what I date picked. If commet out ->set_storage_format( 'd-m-Y' ) I get 2018-07-01. So the code was working as it should, I just can't have been saving the date picker value which is why my output was empty.. doh!
Also I didn't spot the actual date output of echo date( 'd-m-Y' );... thanks.
I've also added back ->set_input_format( 'd-m-Y', 'd-m-Y' ), which now uses d/m/y from the date picker meta box.
Field::make( 'date', 'crb_event_start', 'Event Start' )
->set_storage_format( 'd-m-Y' )
->set_input_format( 'd-m-Y', 'd-m-Y' ),
Silly errors..