Answer the question
In order to leave comments, you need to log in
How to properly sort posts that are closest to the specified date?
I wondered about recommending posts to the current one, for relinking.
Maybe someone can tell you how best to do such sorting in order to display posts that are as close as possible to the specified date (the date of the current post).
Answer the question
In order to leave comments, you need to log in
Let N be the number of posts you want to recommend for the current one. Then we take from the database the first N posts that were published after the specified date and the N last posts that were published before the specified date. We get 2N posts (or less), translate the dates into numbers (strtotime), then calculate D = |дата_поста - указанная_дата|
(modulo). The smaller D , the "closer" the post is to the specified date. Those. sort by D and show N posts with the smallest D .
$day = 1;//указываем число главного поста(к которому тянем другие посты)
$month = 1;//указываем месяц главного поста(к которому тянем другие посты)
$year = 2016;//указываем год главного поста(к которому тянем другие посты)
$args = array(
'orderby' => 'date', //сортируем по полю date
'order' => 'ASC', //сортировка будет от меньшего к большему
'posts_per_page' => 10,//количество записей которые надо вывести
'date_query' => array(
array(
'year' => $year,
'month' => $month,
'day' => $day,
'compare' => '>='
),
),
);
$query = new WP_Query( $args );
while ( $queryt->have_posts() ) {
$query->the_post();
echo get_the_title();//Выводим сам пост
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question