Wordpress教程 2023年05月23日
0 收藏 0 点赞 1,056 浏览 1035 个字

本文来介绍下wordpress的相关文章功能实现代码。

首先还是来说明下这个相关文章是个什么逻辑,文章的相关性都是通过tag标签来关联的,如果两篇文章拥有相同的tag标签,则其中一篇文章的相关文章模块里面会显示另外一篇文章。

直接上wordpress的相关文章功能代码:

<?php
$posttags = get_the_tags();
$category = get_the_category($post->ID);
$the_cate_id = $category[0]->term_id;
$xg_array = array();
if ($posttags) {
    $tags = '';
    foreach ($posttags as $tag) $tags .= $tag->term_id . ',';
    $args = array(
        'post_status' => 'publish',
        'tag__in' => explode(',', $tags),
        'post__not_in' => explode(',', $post->ID),
        'caller_get_posts' => 1,
        'orderby' => 'comment_date',
        'posts_per_page' => 10,
    );
    $xg_array = query_posts($args);
}
if (count($xg_array) == 0) {
    $args = array(
        'post_status' => 'publish',
        'cat' => $the_cate_id,
        'orderby' => 'comment_date',
        'posts_per_page' => 10,
    );
    $xg_array = query_posts($args);
}
foreach ($xg_array as $related) {
    echo ' <li><a href="' . get_permalink($related->ID) . '" rel="external nofollow"  title="' . $related->post_title . '">' . $related->post_title . '</a></li>';
}
wp_reset_query();
?>

以上代码用的是“query_posts”函数,思路是先获取当前文章的tag标签,再通过tag标签来查询同标签的其他文章;如果没有同标签的其他文章,则显示当前文章所在分类下的最新文章。

PS:修改代码里面的数字10可以调整显示最大数量。

以上就是wordpress的相关文章功能实现代码示例了,有其他问题或者对以上代码有不同看法欢迎文章下面评论区域留言交流。

微信扫一扫

支付宝扫一扫

版权: 转载请注明出处:https://www.mizhanw.com/blog/2391.html

相关推荐
宝塔面板里mysql经常自动停止怎么办?
宝塔面板里mysql经常自动停止怎么办? 随着服务器里面的项目越来越多,会发现宝塔面板里mysql经常自动停止。通常这个是因为服务器内存不足…
日期:2023-08-06 点赞:0 阅读:48
更换WordPress网站的域名原始图片地址保持不变
将以上代码添加到你的主题的functions.php文件中,并将$old_domain和$new_domain的值替换为你的旧域名和新域名。…
日期:2023-07-18 点赞:0 阅读:1,004
PHP抓取新浪博客文章内容代码
<?php /** * 新浪博客文章内容解析 */ header("content-type:application/json; ch…
日期:2023-07-14 点赞:0 阅读:716
wp_list_bookmarks()函数删除li标签示例代码【友情链接】
可以使用wp_list_bookmarks()函数的before和after参数。这是更新后的代码: <?php $args = ar…
日期:2023-06-26 点赞:0 阅读:956
WordPress主题分类列表中显示当前分类下的置顶文章,并在下面显示最新发布的文章
在这个代码中,我们首先获取当前分类的ID ($cat_id) 和所有置顶文章的ID数组 ($sticky_posts)。 然后,我们使用 W…
日期:2023-06-25 点赞:0 阅读:319
自动为文章添加相关关键词标签
我们使用的是在当前主题 functions.php 文件中添加代码 <?php function wp_aatags_html2tex…
日期:2023-06-24 点赞:0 阅读:575
发表评论
暂无评论

还没有评论呢,快来抢沙发~