许多博客和网站都采用“上一篇/下一篇”文章导航,方便读者浏览文章。通过“上一篇”和“下一篇”链接,读者可以轻松跳转到前后文章,无需返回主页或文章列表,提升用户体验和参与度。此导航通常显示相邻文章标题,鼓励读者继续阅读,延长网站访问时间。
以下WordPress代码片段实现了这一功能:
/* ---------------------------------------------------------- */
// 文章前后导航代码片段 //
/* ---------------------------------------------------------- */
function sp_post_nav_shortcode( $atts ) {
$atts = shortcode_atts( array(
'type' => 'next', // 默认显示下一篇
), $atts, 'sp_post_nav' );
// 获取上一篇或下一篇
$post = $atts['type'] === 'prev' ? get_previous_post() : get_next_post();
// 箭头图标类名
$arrow_class = $atts['type'] === 'prev' ? 'fas fa-arrow-left' : 'fas fa-arrow-right';
// 容器类名
$link_class = $atts['type'] === 'prev' ? 'prev' : 'next';
if ( $post ) {
$post_title = get_the_title( $post );
$sp_post_nav = '<a class="post-link ' . $link_class . '" href="' . esc_url( get_permalink( $post ) ) . '">';
$sp_post_nav .= '<i class="' . $arrow_class . '"></i>';
$sp_post_nav .= '<div class="inner-wrapper">';
$sp_post_nav .= $atts['type'] === 'prev' ? '<p>上一篇文章:</p>' : '<p>下一篇文章:</p>';
$sp_post_nav .= '<h6>' . $post_title . '</h6>';
$sp_post_nav .= '</div>';
$sp_post_nav .= '</a>';
return $sp_post_nav;
}
return '';
}
add_shortcode( 'sp_post_nav', 'sp_post_nav_shortcode' );
完整代码及更多信息,请访问:https://snippflow.com/snippet/next-previous-post-navigation-in-wordpress/ (Snippflow WordPress 代码片段)