1

Is it possible to query a Wordpress post from a year ago, or the nearest post to that date.

I'd like to have a 'lookback' feature, allowing users to view what we were talking about a year previous.

I've tried looking through the codex but not found any inspiration yet. Any ideas?

2 Answers2

2

You can run a query using WP_Query that will find you a sub-set of posts. Because the date_query function can handle any value that will be recognized by strtotime you can use '-1 year' for convenience.

<?php
$args = array( 
    'post_count' => 1,
    'date_query' => array( array( 'before' => '-1 year' ) ),    
    'posts_per_page' => 1
);
$lookback = new WP_Query( $args ); 

while ( $lookback->have_posts() ) : ?>

    <div>
    <h1>One year ago you posted:</h1>
    <?php $lookback->the_post(); ?>
    </div>

<?php endwhile; ?>
funwhilelost
  • 1,990
  • 17
  • 20
  • thanks - this didn't perfectly work for me, but led me to code that did work `$args = array( 'post_type' => 'podcast', 'date_query' => array( array( 'before' => '-1 year', ), ), 'posts_per_page' => 1 ); $lookback = new WP_Query( $args ); while ( $lookback->have_posts() ) : $lookback->the_post(); ` – Kevin Robinson Feb 15 '17 at 12:17
  • Thanks, @KevinRobinson. If you could chip in by up-voting my answer and marking it correct that'd be much appreciated. – funwhilelost Feb 15 '17 at 23:57
0

The following should work (untested):

global $wpdb;
$nearest_one_year_ago = $wpdb->get_var("SELECT id
FROM $wpdb->posts
ORDER BY ABS( DATEDIFF( post_date, ".date("Y-m-d",strtotime("-1 year", time())." ) ) 
LIMIT 1");

$post = get_post($nearest_one_year_ago);

// ... go on

Explanation: Simply find a working SQL query for your complex query problem and then use $wpdb. However usually using WP_Query is better as long as it can be done with it.

More information: SQL Query to show nearest date? https://www.w3schools.com/sql/func_datediff.asp https://codex.wordpress.org/Class_Reference/wpdb

Community
  • 1
  • 1
Blackbam
  • 17,496
  • 26
  • 97
  • 150