[教程] WordPress获取指定时间段内的文章

查看: 361|回复: 0
wpocn 发表于 2023-2-28 13:35:48
如果需要调用一定时间段内的WordPress文章,可以通过下面的代码实现。

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

  6.         $excludecat = array();
  7.         foreach ( $categories as $category ) {
  8.                 $excludecat[] = $category->cat_ID;
  9.         }

  10.         $args = array(
  11.                 'cat'                 => $cat, // 分类ID
  12.                 'posts_per_page'      => '10', // 显示篇数
  13.                 'ignore_sticky_posts' => true, // 排除置顶
  14.                 'category__not_in'    => $excludecat, // 排除子分类文章
  15.                 'date_query' => array(
  16.                         array(
  17.                                 // 开始年月日
  18.                                 'after'     =>  array(
  19.                                         'year'  => '2022',
  20.                                         'month' => '12',
  21.                                         'day'   => '1',
  22.                                 ),
  23.                                 // 结束年月日
  24.                                 'before'    => array(
  25.                                         'year'  => '2023',
  26.                                         'month' => '12',
  27.                                         'day'   => '31',
  28.                                 ),

  29.                                 'inclusive' => true, // 包括当日
  30.                         ),
  31.                 ),
  32.         );

  33.         $query = new WP_Query( $args );
  34. ?>

  35. <ul>
  36.         <?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();?>
  37.                 <li>
  38.                         <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a>
  39.                 </li>
  40.         <?php endwhile;?>
  41.         <?php wp_reset_postdata(); ?>
  42.         <?php else : ?>
  43.                 <li>
  44.                         暂无文章
  45.                 </li>
  46.         <?php endif;?>
  47. </ul>
复制代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关于本站联系我们FAQ友情链接免责声明生存法则

Build with for "make" Copyright © 2020-2022. Powered by Discuz! GMT+8, 2024-4-25 06:28

快速回复 返回顶部 返回列表