我想在一个页面上显示所有 Wordpress 帖子,并让结果显示如下示例:
9 月(当月)的帖子
1- 第一篇文章 2-秒发帖 3- 第三个帖子
下个月的帖子
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(); ?>
最佳答案
@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 );
获取结果并使用适当的条件设置一个循环链,以获取符合您需要的条件的数据。我没有尝试过,但我认为它解释了我的观点:
// 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;
有什么好处?您只需点击一次数据库,其他一切都由 PHP 作为模板渲染的一部分完成,可以轻松缓存。
关于php - 获取按月分组的 wordpress 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19050288/