小赖子的英国生活和资讯

如何显示缩略图 随机文章 WordPress?

阅读 桌面完整版

上一帖子中, 我们介绍了如何在文章的最后显示 历史的今天. 今天 我们要介绍如何 用缩略图的方式显示一些随机文章 用于增加页面浏览量. 这个有点类似 GOOGLE的显示匹配功能.

你需要定义这样的一个函数 用于获得文章中的第一个图片. 这个函数是用于 如果文章中没有定义缩略图使用的.

 function catch_first_image($post_id) {
   ob_start();
   ob_end_clean();
   $related_post = get_post($post_id);
   $content = $related_post->post_content;
   $output = preg_match_all('//i', $content, $matches);
   return $matches[1][0];
 } 

只需要修改 下面PHP代码中的 $post_num 变量 用于显示图片文章的个数. 然后就可以把代码复制到你想要的地方 比如 Single.php

<style>
.justyyimg {max-width:120px; height: 120px;}
</style>

<div id="related-posts">
    <div class="related" class="clearfix">
      <?php              
      $post_num = 4;// 修改
      $exclude_id = $post->id; 
      $args = array(
          'post_status' => 'publish',
          'post__not_in' => explode(',', $exclude_id),
          'orderby' => 'rand',
          'posts_per_page' => $post_num
      );
      query_posts($args);
      while( have_posts() ) { the_post(); ?>
      <a href="<?php echo the_permalink(); ?>" title="<?php the_title(); ?>" >
      <?php 
          if ( has_post_thumbnail() ) {
            the_post_thumbnail();
          } else {
            $img = catch_first_image(get_the_id());
            if (strlen($img)) {
              echo "<img alt='".get_the_title()."' class='justyyimg' src=\"".$img."\"/>";
            } else {
              echo "<img alt='".get_the_title()."' class='justyyimg' src=\"https://justyy.com/jpg/".mt_rand(1, 20).".jpg\"/>";
            }
          }
      ?></a>
      <?php
        $exclude_id .= ',' . get_the_id();         
      } 
      wp_reset_query();
      ?>
    </div>
</div>          

如果文章已经有缩略图 (has_post_thumbnail) 可以用 e.g. 特色图片. 那么就显示它 (the_post_thumbnail).

          if ( has_post_thumbnail() ) {
            the_post_thumbnail();

之后, 我们会介绍如何改一下这个查询 用于显示相关的文章. 相信不会太难.

英文: 如何显示缩略图 随机文章 WordPress ?

Wordpress博客技术文章

强烈推荐

微信公众号: 小赖子的英国生活和资讯 JustYYUK

阅读 桌面完整版
Exit mobile version