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

知更鸟 WordPress评论110阅读模式

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

文章源自知更鸟-https://zmingcx.com/wordpress-time-period-article.html

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

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

文章源自知更鸟-https://zmingcx.com/wordpress-time-period-article.html

<?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>

代码中加了注释,可以根据实际情况删减,比如不想排除子分类文章可以删除:文章源自知更鸟-https://zmingcx.com/wordpress-time-period-article.html

'category__not_in' => $excludecat,

上面的代码只是基础的写法,更多参数请阅读:官网文档wp_query文章源自知更鸟-https://zmingcx.com/wordpress-time-period-article.html

获取本周发布的WordPress文章列表。 <?php $args = array( 'posts_per_page'...
3012
获取WordPress当日发布的文章列表。 <?php $today = getdate(); $args = arr...
138
文章源自知更鸟-https://zmingcx.com/wordpress-time-period-article.html文章源自知更鸟-https://zmingcx.com/wordpress-time-period-article.html
weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
评论  0  访客  0
匿名

发表评论

匿名网友 填写信息

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

确定