You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP让WP博客“You may have missed”板块显示上周文章

WordPress页脚滑块:仅展示上一周随机文章的实现方案

你需要调整查询参数,让滑块只加载上一周的文章,同时处理跨年时的周数边界问题(比如当前是第1周时,要获取上一年的最后一周),以下是修改后的完整代码:

$current_week = (int) strftime('%U');
$current_year = (int) date('Y');

// 处理跨年情况:如果当前是第1周,上一周就是上一年的最后一周
if ($current_week === 1) {
    $target_week = 52; // 大部分地区一年最后一周是52,部分可能是53,可根据需求调整
    $target_year = $current_year - 1;
} else {
    $target_week = $current_week - 1;
    $target_year = $current_year;
}

$footer_post_type = array(
    'posts_per_page' => 4,
    'post__not_in' => get_option('sticky_posts'),
    'year' => $target_year,
    'week' => $target_week,
    'orderby' => 'rand',
    'post_type' => array('post'),
    'post_status' => 'publish' // 确保只取已发布文章,可选但推荐
);

关键说明:

  • 周数计算:通过判断当前周是否为第1周,处理跨年场景,避免出现周数为0的无效查询
  • 参数替换:把原代码中固定的当前年/周,替换为计算后的目标年/周
  • 额外优化:添加post_status参数确保只加载已发布文章,避免草稿或私密内容被意外展示

如果你的地区周数计算规则不同(比如使用%W而非%U,前者以周一为一周开始),只需把strftime('%U')替换为strftime('%W')即可,同时对应调整跨年时的目标周数。

内容的提问来源于stack exchange,提问作者ejakub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:54:33