使用插件可以轻松显示相关帖子,但是你有没有想过如何使用缩略图显示相关帖子而不使用插件?在本文中,我们将分享两种不同的算法,您可以使用这些算法生成带缩略图的相关帖子,并避免使用任何插件

注意:我们将使用内置的WordPress Post Thumbnail功能。所以最好是你实现这个。

标签的相关帖子

WordPress有这个神奇的分类,称为“帖子标签”,你可以使用它。您可以使用多个关键字标记每个帖子。此算法会找到其他帖子,其中包含当前帖子中的任何一个标签,并将列出它们。

lt;?php $ orig_post = $ post;
全球$ 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 =阵列(
“tag__in”=> $ tag_ids
“post__not_in”=>阵列($后> ID),
“posts_per_page”=> 5,//将显示的相关帖子数。
“caller_get_posts”=大于1
);
$ my_query = new wp_query($ args);
if($ my_query-> have_posts()){

echo“< div id =”relatedposts“>< h3>相关帖子< / h3>< ul>”;

while($ my_query-> have_posts()){
$ my_query-> the_post(); ?>

< li>< div class =“relatedthumb”>< a href =“<?the_permalink()?>” rel =“bookmark”title =“<?php the_title();?>”><?php the_post_thumbnail(); ?>< / A>< / DIV>
                < div class =“relatedcontent”>
                < h3>< a href =“<?the_permalink()?>” rel =“bookmark”title =“<?php the_title();?>”><?php the_title(); ?>< / A>< / H3>
                <?php the_time(“M j,Y”)?>
                < / DIV>
                < /立GT;
&LT ;? }
echo“< / ul>< / div>”;
}
}
$ post = $ orig_post;
wp_reset_query(); ?>

上面的代码查看当前帖子ID和与之关联的所有标签,它使用wp_query函数查找与任何原始标签匹配的所有其他帖子并显示它们。您可以根据需要设置帖子的样式。

优点: Web上的大多数代码都无法在主post循环中使用。由于相关帖子位于主帖之后和评论之上,因此此代码非常有用。我们正在保存主循环的当前帖子ID,然后在相关帖子代码的末尾调用它。通常当你不这样做时,两个帖子ID代码混淆,然后评论开始表现怪异,这可能打破评论,其他插件与评论系统等评论相关。所以这段代码是好的,它工作

用法:将此代码放在 single.php 中的任何位置,这样就可以了。但大部分时间它都位于主循环中的注释之上。

相关帖子分类

此算法会在与当前帖子相同的类别中找到其他帖子,它会列出他们作为相关的职位。这种技术的优点是你的相关帖子部分永远不会有空白点。

<?php $ orig_post = $ post;
全球$ post;
$ categories = get_the_category($ post-> ID);
if($ categories){
$ category_ids = array();
foreach($ categories为$ individual_category)$ category_ids [] = $ individual_category-> term_id;

$ args = array(
“category__in”=> $ category_ids,
“post__not_in”=>阵列($后> ID),
“posts_per_page”=> 2,//将显示的相关帖子数。
“caller_get_posts”=大于1
);

$ my_query = new wp_query($ args);
if($ my_query-> have_posts()){
echo“< div id =”related_posts“>< h3>相关帖子< / h3>< ul>”;
while($ my_query-> have_posts()){
$ my_query-> the_post();?>

< li>< div class =“relatedthumb”>< a href =“<?the_permalink()?>” rel =“bookmark”title =“<?php the_title();?>”><?php the_post_thumbnail(); ?>< / A>< / DIV>
< div class =“relatedcontent”>
< h3>< a href =“<?the_permalink()?>” rel =“bookmark”title =“<?php the_title();?>”><?php the_title(); ?>< / A>< / H3>
<?php the_time(“M j,Y”)?>
< / DIV>
< /立GT;
<
}
echo“< / ul>< / div>”;
}
}
 $ post = $ orig_post;
wp_reset_query(); ?>

此技术使用与上述功能相同的功能,只是我们只使用不同的标准。

如果您正在创建一个新项目,或者在客户的网站上工作,这可能是非常有用。

示例

Add Related Posts with a Thumbnail in WordPress without using Plugins

其他来源:

评论被关闭。