【问题标题】:Related Blog Post in SilverStripeSilverStripe 中的相关博客文章
【发布时间】:2016-08-06 15:03:16
【问题描述】:

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

或者是否有任何解决方案可以更改此 sn-p 以调用所有标签(取决于该博客文章的标签),而不是 (%news%)?:

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

【问题讨论】:

    标签: php silverstripe


    【解决方案1】:

    这是一个BlogPostExtension添加一个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 %>
    

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      相关资源
      最近更新 更多