如何从特定类别中提取最新帖子



我正试图从类别中提取最新的帖子"当地新闻";但我只看到了这一类别的两个帖子中的一个。我不确定是我的if语句和/或while循环导致了这个问题。这是我第一次开发WP主题并使用PHP,所以我有点困惑如何解决这个问题。我不知道如何在不导致严重错误或语法错误的情况下关闭if语句或while循环。

<div class="container">
<div class="row mt-4">
<?php
$args = array(
'category_name' => 'local-news',
'post_type' => 'post' ,
'orderby' => 'date' ,
'order' => 'DESC' ,
'posts_per_page' => 6
);
$q = new WP_Query($args);
$q -> the_post();
?>
if ( $q->have_posts() ) : { 
while ( $q->have_posts() ) : the_post() {
<div class="card-body pb-0">
<div class="latest_news_cont">
<a href="<?php the_permalink() ?>">
<?php the_post_thumbnail(); ?>
</a>
<a href="<?php the_permalink() ?>">
<h5>
<?php the_title(); ?>
</h5>
</a>
<?php the_excerpt(); ?>
<p style="text-align:center;"><a href="<?php the_permalink() ?>" class="readmore_news">Read more</a></p>
<br>
</div>
</div>

<div class="card-body pb-0">
<div class="latest_news_cont">
<a href="<?php the_permalink() ?>">
<?php the_post_thumbnail(); ?>
</a>
<a href="<?php the_permalink() ?>">
<h5>
<?php the_title(); ?>
</h5>
</a>
<?php the_excerpt(); ?>
<p style="text-align:center;"><a href="<?php the_permalink() ?>" class="readmore_news">Read more</a></p>
<br>
</div>
</div>

</div>
</div>

下面我已经修复了我注意到的最初问题:


<?php
$args = array(
'category_name' => 'local-news',
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 6
);
$q = new WP_Query($args);

if ( $q->have_posts() ) :
while ( $q->have_posts() ) : 
$q->the_post();
?>
<div class="card-body pb-0">
<div class="latest_news_cont">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
</a>
<a href="<?php the_permalink(); ?>">
<h5>
<?php the_title(); ?>
</h5>
</a>
<?php the_excerpt(); ?>
<p style="text-align:center;"><a href="<?php the_permalink(); ?>" class="readmore_news">Read more</a></p>
<br>
</div>
</div>
<div class="card-body pb-0">
<div class="latest_news_cont">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
</a>
<a href="<?php the_permalink(); ?>">
<h5>
<?php the_title(); ?>
</h5>
</a>
<?php the_excerpt(); ?>
<p style="text-align:center;"><a href="<?php the_permalink(); ?>" class="readmore_news">Read more</a></p>
<br>
</div>
</div>
<?php
endwhile;
endif;

我发现了它,有很多语法问题,并打开了php标记。

<?php
// the query
$the_query = new WP_Query(array(
'category_name' => 'local-news',
'post_status' => 'publish',
'posts_per_page' => 5,
));
?>
<?php if ($the_query->have_posts()) : ?>
<?php while ($the_query->have_posts()) : $the_query  >the_post(); ?>
<div class="card-body pb-0">
<div class="latest_news_cont">
<a href="<?php the_permalink() ?>">
<?php the_post_thumbnail(); ?>
</a>
<a href="<?php the_permalink() ?>">
<h5>
<?php the_title(); ?>
</h5>
</a>
<?php the_excerpt(); ?>
<p style="text-align:center;"><a href="<?php the_permalink() ?>" class="readmore_news">Read more</a></p>
<br>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php __('No News'); ?></p>
<?php endif; ?>

最新更新