我们大多数 WordPress 站点的文章上下篇都是只显示相应的标题而已,因为我们大多数主题都是直接使用 WordPress 官方提供的 previous_post_link() 与 next_post_link() 这两个函数标签来制定当前文章的上下篇文章。如果想要上下篇实现带有特色图像,我们应该如何实现呢?1、自定…

我们大多数 WordPress 站点的文章上下篇都是只显示相应的标题而已,因为我们大多数主题都是直接使用 WordPress 官方提供的 previous_post_link() 与 next_post_link() 这两个函数标签来制定当前文章的上下篇文章。如果想要上下篇实现带有特色图像,我们应该如何实现呢?

1、自定义一个获取特色图像的函数

WordPress 的 get_the_post_thumbnail 函数只能获取文章的特色图像,如果文章没有特色图像的话就没有图像显示,这样看起来会很别扭,所以我们需要重新定义一个函数:存在特色图像就显示特色图像,不存在特色图像就显示文章第一张图片;文章没有特色图像和图片的情况下,就显示随机问题

将以下代码添加到当前主题的 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' ).'/images/random/'.$random.'.jpg';  }  echo '<img class="home-thumb" src="'.$first_img.'" alt="'.get_post( $post_id )->post_title.'" />';        }}

其中随机图片是放在当前使用主题的 /images/random/ 文件夹下面,后缀名是 .jpg,总共 10 张图片,命名为 1、2、3、…、10。

2、在 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%20echo%20get_permalink(%20$prev_post->ID%20);%20?>"><?php ygj_catch_image($prev_post->ID);?></a> <i class="fa fa-angle-left"></i> 上一篇 <a href="<?php%20echo%20get_permalink(%20$prev_post->ID%20);%20?>"><?php echo $prev_post->post_title; ?></a>        <?php endif; ?>    </div>    <div class="meta-nav">        <?php if (!empty( $next_post )): ?>        <a href="<?php%20echo%20get_permalink(%20$next_post->ID%20);%20?>"><?php ygj_catch_image($next_post->ID);?></a> 下一篇 <i class="fa fa-angle-right"></i> <a href="<?php%20echo%20get_permalink(%20$next_post->ID%20);%20?>"><?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();?>

其实实现带有特色图像的方法还是很简单,只需要分别获得上下篇文章的链接地址、文章标题、特色图像,然后就可以自由组合了。本文重点分享的是方法和思路,其中获取特殊图像的函数还可以增加获取指定图片作为上下篇缩略图等,具体更多的做法和样式就靠大家发挥自己的想象了。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。