Wordpress:使用 WP_Query 或 get_posts() 显示一年前的帖子
Wordpress: Display posts one year ago using WP_Query or get_posts()
我正在尝试显示一年前在今天或之前发布的最后六篇帖子。
我有以下代码:
<?php
$current_month = date('j');
$last_year = date('Y')-1;
?>
<?php query_posts('month='.$current_month.'month='.$current_month.'&year='.$last_year.'&posts_per_page=6');
if (have_posts()): while (have_posts()) : the_post(); ?>
<div class="post-item">
<div class="post-thumb-image">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'grid-thumb' ); ?></a>
</div>
<div class="post-title">
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<p class="post-date"><?php echo get_the_date(); ?></p>
</div>
</div>
<?php endwhile; endif; ?>
它 returns 一年前当月的最后六个帖子。因此,如果现在是 2020 年 12 月 10 日,它将显示 2019 年 12 月的最后六个帖子。
但是,我想显示在一年前今天或之前发布的最后六个帖子,这样它就会显示 2019 年 12 月 10 日或之前发布的最后六个帖子。
另一个问题是上面的代码使用了query_posts()
。这应该是 very inefficient,所以我想知道我是否可以通过使用 WP_Query
或理想情况下 get_posts()
来实现我想要的。
您应该尝试将 WP_Query 与这些类型的参数一起使用:
$args = array(
'date_query' => array(
array(
'column' => 'post_date_gmt',
'before' => '1 year ago',
),
),
'posts_per_page' => 6,
);
$query = new WP_Query( $args );
来源:https://developer.wordpress.org/reference/classes/wp_query/#date-parameters
我多年前为此创建了一个插件。
您可以通过 Github or download it from wordpress plugin repository Plugin.
访问它的源代码
我正在尝试显示一年前在今天或之前发布的最后六篇帖子。 我有以下代码:
<?php
$current_month = date('j');
$last_year = date('Y')-1;
?>
<?php query_posts('month='.$current_month.'month='.$current_month.'&year='.$last_year.'&posts_per_page=6');
if (have_posts()): while (have_posts()) : the_post(); ?>
<div class="post-item">
<div class="post-thumb-image">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'grid-thumb' ); ?></a>
</div>
<div class="post-title">
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<p class="post-date"><?php echo get_the_date(); ?></p>
</div>
</div>
<?php endwhile; endif; ?>
它 returns 一年前当月的最后六个帖子。因此,如果现在是 2020 年 12 月 10 日,它将显示 2019 年 12 月的最后六个帖子。
但是,我想显示在一年前今天或之前发布的最后六个帖子,这样它就会显示 2019 年 12 月 10 日或之前发布的最后六个帖子。
另一个问题是上面的代码使用了query_posts()
。这应该是 very inefficient,所以我想知道我是否可以通过使用 WP_Query
或理想情况下 get_posts()
来实现我想要的。
您应该尝试将 WP_Query 与这些类型的参数一起使用:
$args = array(
'date_query' => array(
array(
'column' => 'post_date_gmt',
'before' => '1 year ago',
),
),
'posts_per_page' => 6,
);
$query = new WP_Query( $args );
来源:https://developer.wordpress.org/reference/classes/wp_query/#date-parameters
我多年前为此创建了一个插件。 您可以通过 Github or download it from wordpress plugin repository Plugin.
访问它的源代码