Display post closest to today’s date

I’m trying to display the post nearest to todays date but so far, no luck.

Lets say today is 18/10/2014, and i have 2 posts, postA has a date 17/10/2014 and postB has a date 21/10/2014, i want postA to be displayed because is nearest today.

Read More

The closest i could get to that result is with this code and i know its still far from what i’m looking for 🙂

$today = date('Ymd');
$date = get_sub_field('fixture-date'); // ACF Date Field

$args = array(
'post_type' => 'events',
'orderby' => 'meta_value',
'meta_key' => $date,
'order' => 'DESC',
'posts_per_page' => 1,
'meta_query' => array(
    'key' => $date,
    'value' => $today
    'compare' => '>='
),

Related posts

Leave a Reply

2 comments

  1. Get the closest post by date

    Here is a function that can return you the post by the closest date.
    I wrote you some comments to explain you the progress.

    You can get only the post->ID or all the post object and do with it what you want.

    function get_closet_post_by_date($date) {
        global $wpdb;
        // Check if there is posts before our $date
        $postA = $wpdb->get_row("SELECT ID, post_date FROM {$wpdb->prefix}posts WHERE post_date < '{$date}' ORDER BY post_date DESC LIMIT 1");
        // Check if there is posts equals or after our $date
        $postB = $wpdb->get_row("SELECT ID, post_date FROM {$wpdb->prefix}posts WHERE post_date >= '{$date}' ORDER BY post_date ASC LIMIT 1");
        /*
        *
        * Convert the posts dates and our $date to time; reduce the post dates from our $date and divide by 60
        * The result of this equals to the seconds before of after our $date
        *
        */
        $postAtime = floor((abs(strtotime($date) - strtotime($postA->post_date)))/(60));
        $postBtime = floor((abs(strtotime($date) - strtotime($postB->post_date)))/(60));
    
    
        // Check which of the posts is closer to our $date
        if($postAtime >= $postBtime) {
            echo $postB->ID; // Post ID
        } else {
            echo $postA->ID; // Post ID
        }
    }
    
    // Run the function
    get_closet_post_by_date('2014-08-12');
    
  2. I did sth like that, it works for me:

    <?php
        $year = strftime('%Y');
    	$month = strftime('%m');
    	$day = strftime('%e');
    	$argsi = array(
    		'numberposts' => 1,
    		'post_type' => $posttype,
    		'orderby' => 'date',
    		'order' => 'ASC',
    		'date_query' => array(
    			'after' => array(
    				'year' => $year,
    				'month' => $month,
    				'day' => $day
    				),
    			'inclusive' => 'true'
    			)
    		);
    	$recent_post = new WP_Query($argsi);
        foreach ($recent_post as $recent) 
        {
          echo get_the_title($recent["ID"]);
          echo get_the_content($recent["ID"]);
        }
    ?>

    it’s important to use functions with ‘get_’. $posttype can be simple ‘post’ or your custom post type.