WordPress无插件实现相关内容调用功能

一般我们从WordPress后台获取的主题中,功能是比较少的,因为优质的主题一般都会需要付费。不过老蒋也是比较喜欢获取简单的主题,然后加一些功能基本上可以实现基本的网站要求,本身网站是用来做内容的,并不是用来好看和丰富功能花哨的。

一般的主题中没有自带相关内容的功能,我们需要通过插件或者自己修改代码实现,使用插件一般会用到WordPress Related Posts插件,后台可以搜索和下载安装。老蒋这里搜索到无需插件即可用代码实现的相关文章调用,也是通过TAG关键字匹配信息的。

第一、代码部分

<h3>这几篇文章你可能也喜欢:</h3>
<ul class="related_posts">
<?php
$post_num = 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 < $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();
}
if ( $i == 0 ) echo '<li>没有相关文章!</li>';
?>
</ul>

红色部分数字10表示调用10篇,我们可以根据实际调整。将代码丢到需要的相关文章位置模板中。

第二、调整 样式

我们可以根据实际的页面调整和添加 .related_posts 样式,包括行距等问题。

本文出处:老蒋部落 » WordPress无插件实现相关内容调用功能 | 欢迎分享( 公众号:老蒋朋友圈 )

公众号 「老蒋朋友圈」获取站长新知 / 加QQ群 【1012423279】获取商家优惠推送