WordPress获取指定时间段内的文章

WordPress评论180阅读模式

如果需要调用一定时间段内的WordPress文章,可以通过下面的代码实现。

WordPress获取指定时间段内的文章-图片1

WordPress获取指定时间段内的文章

<?php
	$cat = '2'; // 分类ID
	// 获取子分类,用于排除子分类文章
	$args = array( 'parent' => $cat );
	$categories = get_categories( $args );

	$excludecat = array();
	foreach ( $categories as $category ) {
		$excludecat[] = $category->cat_ID;
	}

	$args = array(
		'cat'                 => $cat, // 分类ID
		'posts_per_page'      => '10', // 显示篇数
		'ignore_sticky_posts' => true, // 排除置顶
		'category__not_in'    => $excludecat, // 排除子分类文章
		'date_query' => array(
			array(
				// 开始年月日
				'after'     =>  array(
					'year'  => '2022',
					'month' => '12',
					'day'   => '1',
				),
				// 结束年月日
				'before'    => array(
					'year'  => '2023',
					'month' => '12',
					'day'   => '31',
				),

				'inclusive' => true, // 包括当日
			),
		),
	);

	$query = new WP_Query( $args );
?>

<ul>
	<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();?>
		<li>
			<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a>
		</li>
	<?php endwhile;?>
	<?php wp_reset_postdata(); ?>
	<?php else : ?>
		<li>
			暂无文章
		</li>
	<?php endif;?>
</ul>

代码中加了注释,可以根据实际情况删减,比如不想排除子分类文章可以删除:

'category__not_in' => $excludecat,

上面的代码只是基础的写法,更多参数请阅读:官网文档wp_query

WordPress获取指定时间段内的文章-图片2
获取本周发布的WordPress文章列表。 <?php $args = array( 'posts_per_page'...
4394
WordPress获取指定时间段内的文章-图片2
获取WordPress当日发布的文章列表。 <?php $today = getdate(); $args = arr...
207

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

拖动滑块以完成验证