本文将教会你如何为WordPress添加相关文章功能,并提供了标题列表样式和缩略图样式。相关文章的获取思路是:Tags标签相关>同分类下文章,也就是说,先获取标签相同的文章,如果还达不到数量,就调用该分类下的文章补足。获取方法貌似最初来自Willin Kan 大师
实现方法
在主题的 functions.php
的最后一个 ?>
前添加下面的代码:
PS:上面的代码主要是获取图片链接,获取的顺序是:
自定义字段为 thumb
的图片>特色缩略图>文章第一张图片>随机图片/默认图片;
随机图片:请制作10张图片,放在现用主题文件夹下的 images/pic/
目录,图片为jpg格式,并且使用数字 1-10命名,比如 1.jpg;如果你不想用随机图片,请将 倒数第5行 前面的“//”去掉,然后给 倒数第7、9行 前面添加“//”注销,并且在现用主题的 /images/ 目录下添加一张名字为 default_thumb.jpg 的默认图片,这样,就会显示默认图片。
2)将下面的代码添加到 single.php
要显示相关文章的位置:
<h3>相关文章</h3> <ul class="related_img"> <?php $post_num = 4; $exclude_id = $post->ID; $posttags = get_the_tags(); $i = 0; if ( $posttags ) { $tags = ''; foreach ( $posttags as $tag ) $tags .= $tag->term_id . ','; $args = array( 'post_status' => 'publish', 'tag__in' => explode(',', $tags), 'post__not_in' => explode(',', $exclude_id), 'caller_get_posts' => 1, 'orderby' => 'comment_date', 'posts_per_page' => $post_num ); query_posts($args); while( have_posts() ) { the_post(); ?> <li class="related_box" > <div class="r_pic"> <a href="<?php%20the_permalink();%20?>" title="<?php the_title(); ?>" target="_blank"> <img src="<?php%20echo%20post_thumbnail_src();%20?>" alt="<?php the_title(); ?>" class="thumbnail" /> </a> </div> <div class="r_title"><a href="<?php%20the_permalink();%20?>" title="<?php the_title(); ?>" target="_blank" rel="bookmark"><?php the_title(); ?></a></div> </li> <?php $exclude_id .= ',' . $post->ID; $i ++; } wp_reset_query(); } if ( $i < $post_num ) { $cats = ''; foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ','; $args = array( 'category__in' => explode(',', $cats), 'post__not_in' => explode(',', $exclude_id), 'caller_get_posts' => 1, 'orderby' => 'comment_date', 'posts_per_page' => $post_num - $i ); query_posts($args); while( have_posts() ) { the_post(); ?> <li class="related_box" > <div class="r_pic"> <a href="<?php%20the_permalink();%20?>" title="<?php the_title(); ?>" target="_blank"> <img src="<?php%20echo%20post_thumbnail_src();%20?>" alt="<?php the_title(); ?>" class="thumbnail" /> </a> </div> <div class="r_title"><a href="<?php%20the_permalink();%20?>" title="<?php the_title(); ?>" target="_blank" rel="bookmark"><?php the_title(); ?></a></div> </li> <?php $i++; } wp_reset_query(); } if ( $i == 0 ) echo '<div class="r_title">没有相关文章!</div>'; ?> </ul>
PS:第四行$post_num = 4;
表示调用4篇文章,请根据自己需要修改。
css样式自己写,也可参考一下:
.related_posts{margin-top:5px;} .related_img{width:600px;height:210px;} .related_box{float:left;overflow:hidden;margin-top:5px;width:148px;border-right:1px #eee solid} .related_box:hover{background:#f9f9f9} .related_box .r_title{width:auto;height:72px;font-weight:400;font-size:14px;margin:0 10px;overflow:hidden;} .related_box .r_pic{margin:6px} .related_box .r_pic img{width:130px;height:100px;border:1px solid #e1e1e1;background:#fff;padding:2px}
评论前必须登录!
注册