At first, never ever store a date in the format you prefer. Store dates only in the format your database prefer. In case of MySQL the format is YYYY-MM-DD
Let's write a short function to convert a date to the MySQL-format:
function date2mysql( $date ) {
$timestamp = strtotime( $date );
return ( false === $timestamp ) ?
false : date( 'Y-m-d', $timestamp );
}
This function will return a date formated with the MySQL-formaat. If the given date is not a valid date (e.g. '16. Hugo 2013'), the function returns false
.
I expect you have a function to store your data in the database. This could look like this one:
function save_event( $data ) {
$defaults = array(
'date' => '01. January 1970',
'event' => 'Sample event'
);
$data = wp_parse_args( $data, $defaults );
/*
* some code that store your data in the database
*/
}
Before you store the data in the database, you have to convert the date to the right format:
[...]
$data = wp_parse_args( $data, $defaults );
$date = date2mysql( $data['date'] );
// handle cases where the date could not be converted. here setup a default date
if ( false === $date )
$date = '1970-01-01';
$data['date'] = $date;
[...]
If you query your database, the post will be now sorted in the right way but will be displayed wrong. You also need a back-conversion from MySQL-format to a human readable format. WordPress have a build in function for that:
function display_data() {
$events = query_posts(
'post_type=myevents&meta_key=_datepicker&orderby=meta_value&order=ASC&showposts=20'
);
$dateformat = get_option( 'date_format' );
echo '<table>';
echo '<thead><th><td>Date</td><td>Event</td></th></thead>';
echo '<tbody>';
foreach ( $events as $single_event ) {
printf(
'<th><td>%s</td><td>%s</td></th>',
mysql2date( $dateformat, $single_event['date'],
$single_event['event']
);
}
echo '</tbody></table>';
}
mysql2date() format the date with the given format-string (in this example the date format from the WP options).
Summary: Before storing a date in the database, convert it into a MySQL-format. Convert it back into another format only on displaying. Do not convert it before sorting the data or do something else with the data.
query_posts
notWP_query
?filedropper.com
and why we need to register there.