最近我把博客的主题换成了Kratos,界面清爽,自适应。但是在文章底部没有了相关文章的链接,特别是在移动设备上,觉得文章底部太简单,感觉始终少了点什么。

网上搜索发现WordPress有很多支持相关文章的插件,但是我觉得插件会增加很多没有必要的功能,使网站文件变得臃肿。于是我就想通过代码的方式来添加相关文章。

由于我不是开发者,不懂代码,只好做伸手党。在网上找到一段插入相关文章的代码,改一改直接用了:

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
<!-- 相关文章开始 -->
<div class="toolbar">
<h4>相关文章</h4>
<ul class="listbox">
<?php
if ( wp_is_mobile() ){
$post_num = 6; //移动设备显示6篇文章
} else {
$post_num = 10; //非移动设备显示10篇文章
}
$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><a rel="bookmark" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_blank"><?php the_title(); ?></a></li>
<?php
$exclude_id .= ',' . $post->ID; $i ++;
} wp_reset_query();
}
if ( $i == 0 ) echo '<li>没有相关文章!</li>';
?>
</ul>
</div>
<!-- 相关文章结束 -->

根据我自己的需求,我在找到的代码里加入了判断访问设备显示不同条数相关文章的代码。由于我网站分类和标签的设置,我删除了根据文章分类查询相关文章的代码。

根据文章分类查询相关文章的代码是以下部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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><a rel="bookmark" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_blank"><?php the_title(); ?></a></li>
<?php $i++;
} wp_reset_query();
}

将这部分代码插入上面的代码中,就可以同时按标签和分类来查询相关文章。


本站由 @澄哥 使用 Stellar 主题创建。


本页点击量本站点击量次。
您是本站的第个小伙伴
蜀ICP备19037348号-2川公网安备51160202511796号
本站已稳定运行