Чтобы получить месяцы и годы активных публикаций для определенного типа записей в WordPress, вы можете использовать различные методы. Вот несколько подходов с примерами кода:
Метод 1: использование WP_Query
$args = array(
'post_type' => 'your_post_type',
'posts_per_page' => -1, // Get all posts
'post_status' => 'publish', // Only published posts
);
$query = new WP_Query($args);
$months_years = array();
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$post_date = get_the_date('Y-m'); // Get the year and month of the post
$months_years[$post_date] = true; // Store the year and month as a key in the array
}
}
wp_reset_postdata();
$active_months_years = array_keys($months_years);
Метод 2. Использование специального запроса к базе данных
global $wpdb;
$results = $wpdb->get_results(
"SELECT DISTINCT DATE_FORMAT(post_date, '%Y-%m') AS post_month_year
FROM $wpdb->posts
WHERE post_type = 'your_post_type' AND post_status = 'publish'"
);
$active_months_years = array();
foreach ($results as $result) {
$active_months_years[] = $result->post_month_year;
}
Метод 3. Использование функции get_posts
$args = array(
'post_type' => 'your_post_type',
'posts_per_page' => -1, // Get all posts
'post_status' => 'publish', // Only published posts
);
$posts = get_posts($args);
$active_months_years = array();
foreach ($posts as $post) {
$post_date = get_the_date('Y-m', $post->ID); // Get the year and month of the post
$active_months_years[$post_date] = true; // Store the year and month as a key in the array
}
$active_months_years = array_keys($active_months_years);