用惯了文章标题+文章链接的上一篇下一篇样式吗?
前段时间博主在朋友的WordPress博客看到文章缩略图+文章标题+文章链接的上一篇下一篇样式,觉得特别有意思,于是自己也试着实现这样的效果。
网上案例也挺多的,搜出一大堆,整理了下今天分享出来。
效果图

函数代码
将以下代码添加到主题的 functions.php 文件中,用于获取并输出文章的缩略图(优先使用特色图像,若无则从文章内容中提取第一张图片,最后使用随机默认图片)。
// WordPress文章上一篇下一篇显示缩略图
function wptoo_pageturn_thumb($id){
if (has_post_thumbnail($id)) {
echo get_the_post_thumbnail($id, 'thumbnail', array('class' => 'prevnext-thumb'));
} else {
$first_img = '';
$post_content = get_post($id)->post_content;
$output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post_content, $matches);
if (!empty($matches[1][0])) {
$first_img = $matches[1][0];
}
if (empty($first_img)) {
// 定义默认图片路径,请根据你的主题结构调整
$random = mt_rand(1, 10);
$first_img = get_stylesheet_directory_uri() . '/images/random/' . $random . '.jpg';
}
echo '<img class="prevnext-thumb" src="' . esc_url($first_img) . '" alt="' . esc_attr(get_the_title($id)) . '" />';
}
}
使用方法
1. 首先将上面的函数代码添加到主题的 functions.php 文件中。
2. 然后将下面的模板代码添加到 single.php 文件中你希望显示上一篇/下一篇导航的位置(例如在文章内容之后)。
<?php
$current_category = get_the_category(); // 获取当前文章所属分类
$prev_post = get_previous_post($current_category, ''); // 同分类的上一篇文章
$next_post = get_next_post($current_category, ''); // 同分类的下一篇文章
?>
<div class="post-navigation">
<?php if (!empty($prev_post)): ?>
<div class="nav-previous">
<?php wptoo_pageturn_thumb($prev_post->ID); ?>
<a href="<?php echo get_permalink($prev_post->ID); ?>" rel="prev">
<span>上一篇:<?php echo esc_html($prev_post->post_title); ?></span>
</a>
</div>
<?php endif; ?>
<?php if (!empty($next_post)): ?>
<div class="nav-next">
<?php wptoo_pageturn_thumb($next_post->ID); ?>
<a href="<?php echo get_permalink($next_post->ID); ?>" rel="next">
<span>下一篇:<?php echo esc_html($next_post->post_title); ?></span>
</a>
</div>
<?php endif; ?>
</div>
说明与修正:
- 原函数代码中的
ob_start(); ob_end_clean();是多余的,已移除。 - 修正了正则表达式和数组访问的语法错误(如
$matches [1] [0])。 - 为图片输出添加了
esc_url()和esc_attr()函数以提高安全性。 - 将
get_bloginfo('stylesheet_directory')更新为更常用的get_stylesheet_directory_uri()。 - 在模板代码中,为链接添加了语义化的
rel="prev"和rel="next"属性,并为输出内容添加了esc_html()转义。 - 添加了CSS类名(如
post-navigation,nav-previous,nav-next,prevnext-thumb)以便于样式控制。
遇到WordPress建站上的问题可以加入我们的WordPress交流群一起交流分享WordPress建站经验。
WordPress交流群:1038181019