如何在WordPress默认主题Twenty Seventeen中反转文章导航顺序
没问题!在WordPress子主题中实现反转「上一篇/下一篇」导航的时间排序需求,只需要在子主题的functions.php文件中添加以下代码即可:
反转单篇文章的「上一篇/下一篇」导航逻辑
// 调整「上一篇」的查询规则,使其指向更晚发布的文章 add_filter( 'get_previous_post_where', 'reverse_prev_post_where' ); function reverse_prev_post_where( $where ) { global $wpdb; return str_replace( "$wpdb->posts.post_date < '%s'", "$wpdb->posts.post_date > '%s'", $where ); } add_filter( 'get_previous_post_sort', 'reverse_prev_post_sort' ); function reverse_prev_post_sort( $sort ) { return str_replace( 'ORDER BY p.post_date DESC LIMIT 1', 'ORDER BY p.post_date ASC LIMIT 1', $sort ); } // 调整「下一篇」的查询规则,使其指向更早发布的文章 add_filter( 'get_next_post_where', 'reverse_next_post_where' ); function reverse_next_post_where( $where ) { global $wpdb; return str_replace( "$wpdb->posts.post_date > '%s'", "$wpdb->posts.post_date < '%s'", $where ); } add_filter( 'get_next_post_sort', 'reverse_next_post_sort' ); function reverse_next_post_sort( $sort ) { return str_replace( 'ORDER BY p.post_date ASC LIMIT 1', 'ORDER BY p.post_date DESC LIMIT 1', $sort ); }
代码逻辑说明
- 我们通过WordPress的四个过滤钩子,分别修改「上一篇」和「下一篇」的查询条件与排序规则:
- 原生的「上一篇」默认查找更早发布的文章,我们把它的查询条件从
post_date < 当前文章日期改成post_date > 当前文章日期,排序也从降序改成升序,让它指向更晚发布的内容。 - 原生的「下一篇」默认查找更晚发布的文章,我们反向修改查询条件和排序,让它指向更早发布的内容。
- 原生的「上一篇」默认查找更早发布的文章,我们把它的查询条件从
- 这样修改后,页面上右侧的「下一篇」按钮就会跳转到更早发布的文章,完全符合你的需求。
注意事项
- 务必在子主题的
functions.php中添加代码,不要直接修改父主题,避免主题更新时丢失自定义配置。 - 如果你的主题使用了自定义的上下一篇导航函数(而非WordPress原生的
previous_post_link()和next_post_link()),可能需要根据主题的具体实现调整代码,但绝大多数主题都会兼容上述代码。
内容的提问来源于stack exchange,提问作者Ruben
相关产品推荐
相关产品推荐

