一个WordPress循环,显示从刚刚您的类别的4最新帖子

问题描述 投票:0回答:1

我是一个初学者WP,我写了一个循环,从每个我的类别的展示最新的职位,但我需要改进的循环,因此只显示来自4个不同类别的最新帖子。谁能帮我限制类别的数量即时通讯循环通过?这将是大加赞赏。

<div class="latest-updates-container container">
    <div class="row">
        <div class="col-lg-2">
            <div class="latest-update-text">
                LATEST UPDATES
            </div>
        </div>
    </div>
    <div class="latest-updates-outter-wrapper"></div>
    <!--/.container-->
    <div class="">
        <?php

    $do_not_duplicate = array();
    $categories = get_categories();

    foreach ( $categories as $category ) {
        $args = array(
            'cat' => -2,
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => 1,
            'post__not_in' => $do_not_duplicate,
        );
$query = new WP_Query( $args );
if ( $query->have_posts() ) { ?>

        <?php while ( $query->have_posts() ) {

            $query->the_post();
            $do_not_duplicate[] = $post->ID;
    if($i % 5 == 0) { ?>

        <div class="row latest-post">

            <?php
}
?>
            <div class="col-lg-3">
                <div class="my-inner">
                    <h5 id="post-<?php the_ID(); ?>" class="blog-heading">
                        <a href="<?php the_permalink() ?>" rel="bookmark"
                            title="Permanent Link to <?php the_title(); ?>">
                            <?php the_title(); ?></a>
                    </h5>
                    <div class="time-read-now"><?php echo reading_time(); ?>&nbsp; &#183;&nbsp;
                        <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to">read now</a></h4>
                    </div>
                </div>
            </div>
            <?php $i++;
  if($i != 0 && $i % 5 == 0) { ?>
        </div>
        <!--/.row-->
        <div class="clearfix"></div>

        <?php
   } ?>

        <?php } // end while ?>

        </section>

        <?php } // end if

// Use reset to restore original query.
wp_reset_postdata();
    }
?>
    </div>

</div>
</div>

</div>

Its displaying the latest post from all categories, I need to just display 4 categories.
php html wordpress php-7.1
1个回答
0
投票

cat参数允许您filter posts by category ID。你的代码几乎是正确的,你现在需要做的是类别ID传递给WP_Query类:

<?php

$do_not_duplicate = array();
$categories = get_categories();

foreach ( $categories as $category ) {
    $args = array(
        'cat' => $category->term_id, // Get posts from this category ID
        'category__not_in' => array(4, 2), // Exclude posts from categories 4 and 2
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'post__not_in' => $do_not_duplicate,
    );
    $query = new WP_Query( $args );

    // Rest of your code here...
© www.soinside.com 2019 - 2024. All rights reserved.