wordpress中按照标签或分类显示相关文章的代码

以下又是一段可以帮助我们在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
35
36
37
38
39
40
41
<?php
    $max_articles = 7;  // 显示文章的数目,可根据需要调整
    echo '<div id="related-articles" class="sidebox"><h3>相关文章</h3><ul>';
    $cnt = 0;
    $article_tags = get_the_tags();
    $tags_string = '';
    if ($article_tags) {
        foreach ($article_tags as $article_tag) {
            $tags_string .= $article_tag->slug . ',';
        }
    }
    $tag_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&tag=' . $tags_string);
    if ($tag_related_posts) {
        foreach ($tag_related_posts as $related_post) {
            $cnt++;
            echo '<li class="child-' . $cnt . '">';
            echo '<a href="' . get_permalink($related_post->ID) . '">';
            echo $related_post->post_title . '</a></li>';
        }
    }
    // 只有当根据标签显示的相关文章数目不足时,
    // 才会从同分类中的文章中选取补足。
    if ($cnt < $max_articles) {
        $article_categories = get_the_category($post->ID);
        $category_string = '';
        foreach($article_categories as $category) {
            $category_string .= $category->cat_ID . ',';
        }
        $cat_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&category=' . $category_string);
        if ($cat_related_posts) {
            foreach ($cat_related_posts as $related_post) {
                $cnt++;
                if ($cnt > $max_articles) break;
                echo '<li class="child-' . $cnt . '">';
                echo '<a href="' . get_permalink($related_post->ID) . '">';
                echo $related_post->post_title . '</a></li>';
            }
        }
    }
    echo '</ul></div>';
?>

以上参考:http://www.maratz.com/blog/archives/2009/06/15/wordpress-related-articles-by-tags-andor-categories/





本文来源:随便翻翻
原文地址:http://anyff.com/2009/09/related-articles-per-tags-cats/

你可以留言,或者trackback 从你的网站

一条评论

  1. 貌似不错。试试看了

Leave a Reply