WordPress免插件实现相关文章的代码

实现WordPress相关文章有很多的插件,有些主题也自带,刚好喜欢的一个主题没有这个功能,那么我们可以尝试自己来添加。

我们要实现的效果图如下:

相关文章

代码分为两部分,一部分是放到主题文章需要显示的地方,一般放在single.php。

插入到主题的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<div class="relatedposts">
<h3>Related posts</h3>
<?php
  $orig_post = $post;
  global $post;
  $tags = wp_get_post_tags($post->ID);
   
  if ($tags) {
  $tag_ids = array();
  foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
  $args=array(
  'tag__in' => $tag_ids,
  'post__not_in' => array($post->ID),
  'posts_per_page'=>4, // Number of related posts to display.
  'caller_get_posts'=>1
  );
   
  $my_query = new wp_query( $args );
 
  while( $my_query->have_posts() ) {
  $my_query->the_post();
  ?>
   
  <div class="relatedthumb">
    <a rel="nofollow" target="_blank" href="<? the_permalink()?>"><?php the_post_thumbnail(array(150,100)); ?><br />
    <?php the_title(); ?>
    </a>
  </div>
   
  <? }
  }
  $post = $orig_post;
  wp_reset_query();
  ?>
</div>

插入到stlye.css的CSS代码

.relatedposts {width: 640px; margin: 0 0 20px 0; float: left; font-size: 12px;}
.relatedposts h3 {font-size: 20px; margin: 0 0 5px 0; }
.relatedthumb {margin: 0 1px 0 1px; float: left; }
.relatedthumb img {margin: 0 0 3px 0; padding: 0;}
.relatedthumb a {color :#333; text-decoration: none; display:block; padding: 4px; width: 150px;}
.relatedthumb a:hover {background-color: #ddd; color: #000;}

没有对标题字段截断,如果显示超过两排可能会有错乱,需要调整下.relatedthumb 的高度。如果你的主题文章区域比较宽,需要调整下.relatedposts 的宽度。

上面是比较基础的代码,你可以根据自己的需要来调整。

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this post. TrackBack URL