Сравните значения даты в WordPress WP_Query

#wordpress #compare

#wordpress #Сравнить

Вопрос:

Я запускаю веб-сайт WordPress с примерно 35 000 таможенными постами. У каждого сообщения есть дата значения дня рождения (формат ДД / ММ / ГГГГ), хранящаяся в поле ACF с именем birthday

Пример :

 $birtday_date = get_field("birthday"); //example 02/07/1955
  

Я хотел бы выполнить 2 запроса, чтобы сравнить значение каждого поста birthday с 34999 другими значениями дат рождения в моем WordPress, посчитать и отобразить количество людей старше и младше.
Вот мой код, но он не работает, поскольку я действительно не понимаю, как сравнивать значение

Можете ли вы помочь мне с этим?

 <?php
$args = array(  // args and query to look for older people that $birthday_date
'posts_per_page' => -1,
'post_type' => 'people',
'meta_key' => 'birthday',
'meta_value' => $birthday_date,
'compare' => '>',
'type' => 'DATE'

);
$query = new WP_Query($args);
$superior = $query->found_posts;
wp_reset_query();



$args2 = array(  // args and query to look for younger people that $birthday_date
'posts_per_page' => -1,
'post_type' => 'people',
'meta_key' => 'birthday',
'meta_value' => $birthday_date,
'compare' => '<',
'type' => 'DATE'

);
$query2 = new WP_Query($args2);
$inferior = $query2->found_posts;
wp_reset_query();

echo $superior; // should display the number of older people but display number of people born the same day than $birthday_date
echo $inferior; // should display the number of younger people but display number of people born the same day than $birthday_date
  

Спасибо за вашу помощь.

С уважением.

Ответ №1:

Вероятно, вам нужен только один фактический запрос здесь, я бы предложил использовать только get_posts вместо этого, поскольку вы ничего не зацикливаете. И вы можете просто посчитать разницу от общего количества записей в типе записи.

 <?php

$birthday_date = get_field("birthday");

// Count the total number of posts in the post type and get the ones that are published.  Note this shorthand only works in PHP5

$total_posts = wp_count_posts('people')->publish;

// Use this for PHP4
// $count_posts = wp_count_posts('people');
// $total_posts = $count_posts->publish;

$args = array(  // args and query to look for older people that $birthday_date
'posts_per_page' => -1,
'post_type' => 'people',
'meta_query' => array(
   'key' => 'birthday',
   'value' => $birthday_date,
   'compare' => '>',
   'type' => 'DATE'
)
);

// Get the posts with the older birthdays
$older_birthdays = get_posts($args);

// Count the number of posts in the older birthdays 
$num_of_older_bdays = count($older_birthdays);

// Calculate the other birthdays remaining
$num_of_younger_bdays = $total_posts - $older_birthdays;

// Display your birthday counts
echo $num_of_older_bdays;
echo $num_of_younger_bdays;