在Wordpress中按日期过滤最新帖子

时间:2020-07-02 17:59:07

标签: php wordpress

每次发布​​新文章时,我只希望过滤最新文章并显示在页面上。

但是,使用所获得的代码是我理想地实现此目标的地方。因此,基本上,我将使用下面获得的代码两次-一次将最新的artcile展示为顶级博客文章(样式将有所不同),然后重用此代码过滤所有其他文章。

下面是代码;

<article>
<?php if(have_posts()) : while (have_posts()) : the_post(); ?>
<h1 style="text-transform:uppercase;"><?php the_title(); ?></h1>
<h4>Posted on: <?php the_time('F jS, Y') ?></h4>
<p><?php the_content(__('Read More')); ?></p>
<?php endwhile; else: ?>
<p><?php _e('Sorry, there are no posts available at the time.'); ?></p>
<?php endif; ?>
</article>

请问如何实现?

2 个答案:

答案 0 :(得分:0)

那应该是您想要的。

<!-- Start most recent post loop here -->
<?php
$query = new wp_query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => '1', 'orderby' => 'post_date', 'order' => 'ASC' ) );  if ( $query->have_posts() ): ?>
<?php while ( $query->have_posts() ): $query->the_post(); ?>
<!-- Start post template here -->
<div style="padding:15px;border:1px solid red;margin-bottom:15px;"><a aria-label="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
<!-- End post template here -->
<?php endwhile; else: ?>
<?php endif; ?>
<!-- End most recent post loop here -->

<!-- Start all post exept first loop here -->
<?php
$query = new wp_query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => '-1', 'orderby' => 'post_date', 'order' => 'ASC', 'offset' => '1' ) );  if ( $query->have_posts() ): ?>
<?php while ( $query->have_posts() ): $query->the_post(); ?>
<!-- Start post template here -->
<div style="padding:15px;border:1px solid grey;margin-bottom:15px;"><a aria-label="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
<!-- End post template here -->
<?php endwhile; else: ?>
<?php endif; ?>
<!-- End all post exept first loop here -->

答案 1 :(得分:0)

由于您要在顶部分别显示最新的文章,并以不同的样式显示,而在其下方的所有其他文章都以不同的样式显示,则可以使用它。

<article>
<?php $counter = 1; ?>
<?php if(have_posts()) : while (have_posts()) : the_post(); ?>
<?php if($counter == 1) { ?>
<!-- Use this block to style your top most latest post -->
<h1 style="text-transform:uppercase;"><?php the_title(); ?></h1>
<h4>Posted on: <?php the_time('F jS, Y') ?></h4>
<p><?php the_content(__('Read More')); ?></p>
<?php $counter = $counter + 1; ?>
<!-- Top Block Ends -->
<?php } else { ?>
<!-- Use this block to style other remaining posts -->
<h1 style="text-transform:uppercase;"><?php the_title(); ?></h1>
<h4>Posted on: <?php the_time('F jS, Y') ?></h4>
<p><?php the_content(__('Read More')); ?></p>
<!-- Bottom Block Ends -->
<?php } ?>
<?php endwhile; else: ?>
<p><?php _e('Sorry, there are no posts available at the time.'); ?></p>
<?php endif; ?>
</article>

更改代码中定义的每个块所需的h1标签或样式或颜色,您将能够获得所需的效果。