星期三 , 22 1 月 2025

一个经典的新闻列表的循环,循环所有分类和文章

<?php
// Get the first three categories
$categories = get_categories(array(
    'orderby' => 'name',
    'order'   => 'ASC',
    'number'  => 3
));

// Array of category titles and their corresponding labels
$category_labels = array(
    'COMPANY' => 'Company_News',
    'INDUSTRY' => 'Industry_news',
    'QUESTION' => 'Q&A'
);

// Loop through each category
foreach ($categories as $index => $category) :
    $category_name = strtoupper($category->name);
    $label = isset($category_labels[$category_name]) ? $category_labels[$category_name] : $category_name;
    $column_class = 'col-' . ['l', 'm', 'r'][$index];
?>
    <div class="<?php echo $column_class; ?> wow fadeInUp animated" data-wow-duration="1s" data-wow-delay=".1s">
        <div class="g-tit-2">
            <a href="<?php echo get_category_link($category->term_id); ?>" class="more">Read More+</a>
            <span>News</span><em><?php echo $category_name; ?></em>
        </div>
        <div class="myscroll">
            <?php if ($category_name !== 'QUESTION') : ?>
                <ul class="ul-news">
                    <?php
                    $query = new WP_Query(array(
                        'cat' => $category->term_id,
                        'posts_per_page' => 6
                    ));
                    while ($query->have_posts()) : $query->the_post();
                    ?>
                        <li>
                            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                                <span>[<?php echo $label; ?>]</span><?php the_title(); ?>
                            </a>
                        </li>
                    <?php
                    endwhile;
                    wp_reset_postdata();
                    ?>
                </ul>
            <?php else : ?>
                <ul class="ul-ask">
                    <?php
                    $query = new WP_Query(array(
                        'cat' => $category->term_id,
                        'posts_per_page' => 2
                    ));
                    while ($query->have_posts()) : $query->the_post();
                    ?>
                        <li>
                            <h5><span>Ask</span>:<?php the_title(); ?></h5>
                            <p><span>Answer:</span><?php the_content(); ?></p>
                        </li>
                    <?php
                    endwhile;
                    wp_reset_postdata();
                    ?>
                </ul>
            <?php endif; ?>
        </div>
    </div>
<?php endforeach; ?>