WordPress文章实现上下篇按钮并带有图像
将以下代码添加到当前主题的 functions.php 文件即可
//上下篇缩略图
function ygj_catch_image($id){
if (has_post_thumbnail($id)) { echo get_the_post_thumbnail( $id, '', '' );
} else {
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', get_post( $id )->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$random = mt_rand(1, 10);
$first_img= get_bloginfo ( 'stylesheet_directory' ).'/img/random/'.$random.'.jpg';
}
echo '<img class="home-thumb" src="'.$first_img.'" alt="'.get_post( $post_id )->post_title.'" />';
}
}
其中随机图片是放在当前使用主题的 /img/random/ 文件夹下面,后缀名是 .jpg。
在single.php文件的适当位置添加以下代码:
<div class="nav-single">
<?php
$current_category = get_the_category();//获取当前文章所属分类ID
$prev_post = get_previous_post($current_category,'');//与当前文章同分类的上一篇文章
$next_post = get_next_post($current_category,'');//与当前文章同分类的下一篇文章
?>
<div class="meta-nav">
<?php if (!empty( $prev_post )): ?>
<a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php ygj_catch_image($prev_post->ID);?></a> <i class="fa fa-angle-left"></i> 上一篇 <a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo $prev_post->post_title; ?></a>
<?php endif; ?>
</div>
<div class="meta-nav">
<?php if (!empty( $next_post )): ?>
<a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php ygj_catch_image($next_post->ID);?></a> 下一篇 <i class="fa fa-angle-right"></i> <a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo $next_post->post_title; ?></a>
<?php endif; ?>
</div>
</div>
以上代码是显示同一分类的上下篇,如果不想显示同一分类的上下篇,可以直接把以下代码:
<?php
$current_category = get_the_category();//获取当前文章所属分类ID
$prev_post = get_previous_post($current_category,'');//与当前文章同分类的上一篇文章
$next_post = get_next_post($current_category,'');//与当前文章同分类的下一篇文章
?>
改为:
<?php
$prev_post = get_previous_post();
$next_post = get_next_post();
?>
补充:
get_the_post_thumbnail_url //可只调取图片的链接地址,不附加图片的基本样式。