SilverStripe中的相关博客文章

时间:2016-08-06 15:03:17

标签: php silverstripe

我们如何在SilverStripe中获取与类别或标签相关的相关博客文章?

或者是否有任何解决方案可以更改此代码段以调用所有标记(取决于该博客帖子的标记),而不是(%news%)?:

function LatestNews($num = 5) { 
    return DataObject::get("ArticlePage", "Tags LIKE '%news%' ", "Date DESC", "", $num); 
}

1 个答案:

答案 0 :(得分:4)

以下是BlogPost Extension添加RelatedCategoryPosts函数和RelatedTagPosts函数:

class BlogPostExtension extends DataExtension {

    public function RelatedCategoryPosts() {
        $relatedPosts = ArrayList::create();

        foreach ($this->owner->Categories() as $category) {
            $relatedPosts->merge($category->BlogPosts());
        }

        $relatedPosts->removeDuplicates();
        $relatedPosts->remove($relatedPosts->byID($this->owner->ID));

        return $relatedPosts;
    }

    public function RelatedTagPosts() {
        $relatedPosts = ArrayList::create();

        foreach ($this->owner->Tags() as $tag) {
            $relatedPosts->merge($tag->BlogPosts());
        }

        $relatedPosts->removeDuplicates();
        $relatedPosts->remove($relatedPosts->byID($this->owner->ID));

        return $relatedPosts;
    }
}

要启用此功能,我们将此扩展名添加到config.yml

BlogPost:
  extensions:
    - BlogPostExtension

现在,在我们的自定义BlogPost模板中,我们可以调用这些函数来检索相关帖子:

<% if $RelatedCategoryPosts %>
    <h2>Related posts</h2>
    <ul>
        <% loop $RelatedCategoryPosts %>
            <li><a href="$Link">$Title</a></li>
        <% end_loop %>
    <ul>
<% end_if %>