I'm trying to display a list of upcoming football matches in order of kick off. The code I currently have lists the dates in the correct order but the posts ordering is incorrect.
<?php
$previews_new_loop = array(
'posts_per_page' => -1,
'post_type' => 'football_match',
'meta_key' => 'kick-off-date',
'orderby' => 'meta_value',
'order' => 'ASC',
);
$wpquery = new WP_Query( $previews_new_loop );
$posts = $wpquery->get_posts();
$ordered_posts = array();
foreach ( $posts as $post ) {
$meta_value = get_post_meta( $post->ID, 'kick-off-date', true );
if ( !$meta_value ) {
continue;
}
$date = date( 'ddmmyyyy', strtotime( $meta_value ) );
$ordered_posts[$date][] = $post;
}
foreach ( $ordered_posts as $post_date => $posts ) {
foreach ( $posts as $post ):
endforeach;
}
I'm trying to display a list of upcoming football matches in order of kick off. The code I currently have lists the dates in the correct order but the posts ordering is incorrect.
<?php
$previews_new_loop = array(
'posts_per_page' => -1,
'post_type' => 'football_match',
'meta_key' => 'kick-off-date',
'orderby' => 'meta_value',
'order' => 'ASC',
);
$wpquery = new WP_Query( $previews_new_loop );
$posts = $wpquery->get_posts();
$ordered_posts = array();
foreach ( $posts as $post ) {
$meta_value = get_post_meta( $post->ID, 'kick-off-date', true );
if ( !$meta_value ) {
continue;
}
$date = date( 'ddmmyyyy', strtotime( $meta_value ) );
$ordered_posts[$date][] = $post;
}
foreach ( $ordered_posts as $post_date => $posts ) {
foreach ( $posts as $post ):
endforeach;
}
I have the code below (started from yours) setup as a shortcode and it works fine. When I change the direction 'ASC' to 'DESC', the sort order changes as well, so it is not 'luck' that posts are in the correct order. It assumes that the dates are stored yyyymmdd. NOTE that one must remove the line:
$date = date('ddmmyyyy', strtotime($meta_value));
if the dates are already stored ddmmyyyy.
function sort_by_date() {
$previews_new_loop = array(
'posts_per_page' => -1,
'post_type' => 'article', //'football_match',
'meta_key' => 'kick-off-date',
'orderby' => 'meta_value',
// 'order' => 'ASC',);
'order' => 'DESC',);
$wpquery = new WP_Query($previews_new_loop);
$posts = $wpquery->get_posts();
$ordered_posts = array();
foreach ($posts as $post) {
$meta_value = get_post_meta($post->ID, 'kick-off-date', true);
if (!$meta_value) {
continue;
}
//$date = date('ddmmyyyy', strtotime($meta_value));
$ordered_posts[$meta_value][] = $post;
}
$html = '<pre>'.print_r($ordered_posts, true).'</pre>';
return $html;
}
add_shortcode('sort_by_date','sort_by_date');
'order' => 'ASC',);
– Gazi Commented Dec 12, 2018 at 13:05