文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。

问题
最近升级了一下博客主题然后发现D8主题自带的"与本文相关的文章"生成逻辑很蠢,而且也不支持什么选项。默认它只会对标签 (Tag) 做一个并集搜索然后按最近的评论排序,很多文章包含一些热门标签,就导致利用这个算法生成的相关文章列表几乎一模一样。理论上"与本文相关的文章"应该对所有的标签进行关联匹配,共享的标签越多表明越匹配。
解决方案
本来打算自己写一个标签匹配逻辑,但在插件库搜索了一下发现前人已经把轮子造好了。"YARPP – Yet Another Related Posts Plugin",这个插件支持多种可以自定义的相关文章排序算法,它还提供一个函数 "yarpp_get_related()" 允许你在自己的模板里调用这个插件,完美。
D8主题的相关文章函数模板在 "\wp-content\themes\d8\modules\related.php",打开之后修改代码调用这个插件获取相关文章然后按照模板的风格输出就好了。插件的配置可以在后台进行修改,无需再更改主题模板代码了。
完整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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<ul> <?php $exclude_id = $post->ID; $posttags = get_the_tags(); $i = 0; $limit = !dopt("d_related_count") ? 12 : dopt("d_related_count"); if (function_exists("yarpp_get_related")) { $related_posts = yarpp_get_related(); if (!empty($related_posts)) { foreach ($related_posts as $related_post) { echo '<li><a href="' . get_permalink($related_post->ID) . '">', $related_post->post_title, "</a></li>"; $exclude_id .= "," . $related_post->ID; $i++; } } } else { if ($posttags) { $tags = ""; foreach ($posttags as $tag) { $tags .= $tag->name . ","; } $args = [ "post_status" => "publish", "tag_slug__in" => explode(",", $tags), "post__not_in" => explode(",", $exclude_id), "ignore_sticky_posts" => 1, "orderby" => "comment_date", "posts_per_page" => $limit, ]; query_posts($args); while (have_posts()) { the_post(); echo '<li><a href="' . get_permalink() . '">', get_the_title(), "</a></li>"; $exclude_id .= "," . $post->ID; $i++; } wp_reset_query(); } } if ($i < $limit) { $cats = ""; foreach (get_the_category() as $cat) { $cats .= $cat->cat_ID . ","; } $args = [ "category__in" => explode(",", $cats), "post__not_in" => explode(",", $exclude_id), "ignore_sticky_posts" => 1, "orderby" => "comment_date", "posts_per_page" => $limit - $i, ]; query_posts($args); while (have_posts()) { the_post(); echo '<li><a href="' . get_permalink() . '">', get_the_title(), "</a></li>"; $i++; } wp_reset_query(); } if ($i == 0) { echo "<li>" . __("暂无相关文章!", "TBL") . "</li>"; } ?> </ul> |
转载请注明:Slyar Home » D8主题相关文章代码优化