这是我起草的一些代码。它可能没有使用最佳实践,甚至事实上也不起作用,因为我没有测试过它,但理论上它应该起作用。:)
<?php
/**
* Retrieve the closest post from a set time from today.
*
* @param integer $daysago the number of days
* @return integer the ID of the post from long ago
**/
function wpse38126_filterfoward($where = \'\', $daysago) { $where .= " AND post_date > \'" . date(\'Y-m-d\', strtotime(\'-\' . $daysago . \' days\')) . "\'"; return $where; }
function wpse38126_filterbackward($where = \'\', $daysago) { $where .= " AND post_date >= \'" . date(\'Y-m-d\', strtotime(\'-\' . $daysago*2 . \' days\')) . "\'" . " AND post_date <= \'" . date(\'Y-m-d\', strtotime(\'-\'.$daysago.\' days\')) . "\'"; }
function wpse38126_limits($limits) { return 1; }
function wpse38126_postfromlongago( $daysago = \'\') {
$month = date(\'n\', strtotime(\'-\' . $daysago . \' days\'));
$day = date(\'j\', strtotime(\'-\' . $daysago . \' days\'));
$year = date(\'Y\', strtotime(\'-\' . $daysago . \' days\'));
$query = new WP_Query(array(
\'month\' => $month,
\'day\' => $day,
\'year\' => $year ));
if($query->have_posts()) { while($query->have_posts()) { $query->the_post();
return $post->ID;
} } else {
add_filter( \'posts_where\', \'wpse38126_filterfoward\' );
add_filter( \'post_limits\', \'wpse38126_limits\' );
$fowardintime = new WP_Query( $query_string . \'&order=ASC&orderby=date\' );
remove_filter( \'posts_where\', \'filtwpse38126_filterfowarder\' );
remove_filter( \'post_limits\', \'wpse38126_limits\' );
add_filter( \'posts_where\', \'wpse38126_filterbackward\' );
add_filter( \'post_limits\', \'wpse38126_limits\' );
$backwardintime = new WP_Query( $query_string );
remove_filter( \'posts_where\', \'wpse38126_filterbackward\' );
remove_filter( \'post_limits\', \'wpse38126_limits\' );
// set up posts
if($fowardintime->have_posts) { while($fowardintime->have_posts()) { $fowardintime->the_post();
$fowardintime_id = $post->ID; $fowardintime_date = get_the_date( \'Y/m/d g:i:s A\' );
}
if($backwardintime->have_posts) { while($backwardintime->have_posts()) { $backwardintime->the_post();
$backwardintime_id = $post->ID; $backwardintime_date = get_the_date( \'Y/m/d g:i:s A\' );
}
// do some complicated logical comparisons
if($fowardintime_id && !$backwardintime_id) {
return $fowardintime_id;
} elseif ($backwardintime_id && !$fowardintime_id) {
return $backwardintime_id;
} else {
$foward = strtotime($fowardintime_date) - strtotime(\'-\' . $daysago . \' days\');
$backward = strtotime(\'-\' . $daysago . \' days\') - strtotime($backwardintime_date);
if ($foward < $backward) {
return $fowardintime_id;
} else {
return $backwardintime_id;
}
}
}
}
?>
哦,这是用法。假设您想发布一年前该帖子的链接。
<?php $post_id = wpse38126_postfromlongago(365); ?>
<a href="<?php echo get_permalink( $post_id ); ?>">My link to a post or page</a>
任何人都可以免费帮助改进它。