Files
agroexpert/partials/related-posts.php
2026-03-05 22:37:13 +03:00

57 lines
1.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
// Получаем количество постов из параметра или устанавливаем по умолчанию 4
$posts_per_page = isset($args['posts_per_page']) ? intval($args['posts_per_page']) : 4;
$current_post_id = get_the_ID();
// Получаем категории текущего поста
$categories = get_the_category($current_post_id);
// Базовая настройка запроса
$query_args = array(
'post__not_in' => array($current_post_id),
'posts_per_page' => $posts_per_page,
);
if ($categories) {
// Проверяем, есть ли среди категорий поста категория с ID 21
$has_category_21 = false;
foreach ($categories as $category) {
if ($category->term_id == 21) {
$has_category_21 = true;
break;
}
}
if ($has_category_21) {
// Если есть категория 21, показываем посты из категорий 21 и 19
$query_args['cat'] = '21,19';
} else {
// Иначе используем все категории поста
$category_ids = array_map(function ($category) {
return $category->term_id;
}, $categories);
$query_args['category__in'] = $category_ids;
}
} else {
// Если категорий нет, используем категорию 19
$query_args['cat'] = 19;
}
$related_posts_query = new WP_Query($query_args);
if ($related_posts_query->have_posts()) {
echo '<div class="article-section__title">Читайте также:</div>';
echo '<div class="articles-preview">';
while ($related_posts_query->have_posts()) {
$related_posts_query->the_post();
get_template_part('content', 'post');
}
echo '</div>';
wp_reset_postdata();
}
?>