<?php
global $wpdb; // Глобальная переменная для работы с базой данных


$included_category_ids = array(740); // Начально включаем саму рубрику 740
$child_categories = get_term_children(740, 'category');
if (!empty($child_categories)) {
    $included_category_ids = array_merge($included_category_ids, $child_categories);
}

// Формируем часть запроса для IN оператора
$included_category_ids_in = implode(',', array_map('intval', $included_category_ids));

$query = $wpdb->prepare("
    SELECT DISTINCT p.ID, p.post_title, p.post_content, m.meta_value AS top_participation_position
    FROM $wpdb->posts p
    INNER JOIN $wpdb->postmeta m ON p.ID = m.post_id
    LEFT JOIN $wpdb->term_relationships tr ON p.ID = tr.object_id
    LEFT JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
    WHERE p.post_type = 'post'
    AND m.meta_key = 'top_participation_position'
    AND m.meta_value != ''
    AND tt.term_id IN ($included_category_ids_in)
    ORDER BY CAST(m.meta_value AS UNSIGNED) ASC
");


$top_posts = $wpdb->get_results($query);

// Вывод результатов
if (!empty($top_posts)) {
    foreach ($top_posts as $post) {
        $permalink = get_permalink($post->ID);
        $title = get_the_title($post->ID);
?>
        <div class="most-read__link">
            <a href="<?php echo esc_url($permalink); ?>" class="most-read__link-inner text-13 link-icon-after">
                <?php echo esc_html($title); ?>
            </a>
        </div>
<?php
    }
} else {
    echo '<p>Нет просмотренных постов.</p>';
}
?>