Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // List custom posts in ascending order of the maximum date
- // contained in a list of dates in a custom field. The dates
- // are in d-m-yyyy format.
- // Example meta_value: 1-10-2011, 17-2-2013, 25-6-2014
- $post_type = 'parks';
- $meta_key = 'dates_of_leaving';
- // Get post IDs and dates_of_leaving
- $sql = "
- SELECT p.ID, pm.meta_value AS dates
- FROM $wpdb->posts p
- JOIN $wpdb->postmeta pm ON (p.ID = pm.post_id)
- WHERE p.post_type = '$post_type'
- AND pm.meta_key = '$meta_key'
- AND p.post_status = 'publish'
- ORDER BY p.ID ASC
- ";
- $rows = $wpdb->get_results($sql);
- // Get the max date for each ID. Save the ID and date for sorting
- $for_sorting = array();
- $current_id = 0;
- foreach ($rows as $row) {
- $newdates = array();
- $olddates = explode(',',$row->dates);
- // Reformat and save the dates
- foreach ($olddates as $olddate) {
- if (preg_match('/(\d+)-(\d+)-(\d{4})/', $olddate, $matches ) ) {
- $newdates[] = $matches[3] .
- str_pad($matches[2], 2, '0', STR_PAD_LEFT) .
- str_pad($matches[1], 2, '0', STR_PAD_LEFT);
- }
- }
- rsort($newdates); // Sort the dates high to low
- //print_r('<pre>DATES:');print_r($newdates);print_r('</p>');
- if ($newdates) {
- $for_sorting[] = array('ID' => $row->ID, 'date' => $newdates[0]);
- }
- }
- //print_r('<pre>FORSORTING:');print_r($for_sorting);print_r('</p>');
- // Now, sort the array with ID and date
- usort($for_sorting, function($a, $b) {
- return $a['date'] - $b['date'];});
- //print_r('<pre>SORTED:');print_r($for_sorting);print_r('</p>');
- // Get just the IDs, in order
- $id_array = array();
- foreach ($for_sorting as $sorted) {
- $id_array[] = $sorted['ID'];
- }
- // Show posts in order of post__in array
- $args = array(
- 'post_type' => $post_type,
- 'post__in' => $id_array,
- 'ignore_sticky_posts' => 1, // Stickies will mess this up
- );
- query_posts($args);
- if (have_posts()) :
- usort($wp_query->posts, function($a, $b) use ($id_array) {
- return array_search($a->ID, $id_array) - array_search($b->ID, $id_array);
- });
- while (have_posts()) :
- // Put your own loop code here
- the_post();
- echo "<p>ID: $post->ID</p>";
- endwhile;
- endif;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement