得到按月分组的wordpress帖子

use*_*886 2 php wordpress

我想在一个页面上显示所有Wordpress帖子,结果显示如下:

9月的帖子(当月)

1-第一篇第二篇第二篇第三篇第三篇文章

下个月的帖子

2-第一帖子2-第二帖子3-第三帖子

我已完成此结果以显示按月订购的所有帖子,但我无法将它们分组并使帖子显示为每个月的一组:

 <?php
$month = date('M');
$arrgs = array('orderby' => $month);
$myposts = get_posts($arrgs);
foreach($myposts as $post) :
setup_postdata($post);
?>
<div class="post-item">
    <div class="post-info">
        <h2 class="post-title">
            <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>">
                <?php the_title(); ?>
            </a>
        </h2>
        <p class="post-meta">Posted by <?php the_author(); ?> Published in <strong><?php echo $month; ?></strong></p>
    </div>
</div>
<?php endforeach; wp_reset_postdata(); ?>
Run Code Online (Sandbox Code Playgroud)

Mar*_*llo 5

@zillaofthegods这里是我的解决方案:我只使用1个查询来获取我要显示的所有帖子,然后使用PHP来完成繁重的任务.一个好主意是要求将年份和月份作为额外的列,因为我们将来需要这些列.

global $wpdb; // Don't forget

$collection = $wpdb->get_results("
  SELECT YEAR(p.post_date) AS post_year, MONTH(p.post_date) AS post_month, p.*
  FROM {$wpdb->posts} AS p
  WHERE p.post_type = 'post' AND p.post_status = 'publish'
  ORDER BY p.post_date DESC
", OBJECT );
Run Code Online (Sandbox Code Playgroud)

获取结果并使用适当的条件设置一系列循环,以获得具有所需条件的数据.我没试过这个,但我认为它解释了我的观点:

// Loop once to grab the years
foreach ( $collection as $year ):

  // Loop for a second time to grab the months inside a year
  foreach ( $collection as $month ):

    // Continue unless years match
    if ( $month->post_year != $year ) continue;

    // Loop one more time to grab the posts inside the month, inside the year
    foreach ( $collection as $post ):

      // Continue unless months and years match
      if ( $post->post_year != $year || $post->post_month != $month ) continue;

      // You can use the posts data here

    endforeach;

  endforeach;

endforeach;
Run Code Online (Sandbox Code Playgroud)

有什么好处?你点击你的数据库一次,其他一切都由PHP完成,作为模板渲染的一部分,可以很容易地进行缓存.