Quantcast
Channel:
Viewing all articles
Browse latest Browse all 4235

Re: Prev/Next when ordered by DATE?

$
0
0

Assuming NewsArticle is a DataObject and not a SiteTree/Page subclass, you can try this:

public function NextArticle() {
$next = DataObject::get("NewsArticle","NewsArticle.Date <= '{$this->Date}' AND NewsArticle.ID <> {$this->ID}","NewsArticle.Date.DESC, NewsArticle.ID ASC","","0,1");
if ($next && $next->exists()) {
return $next->First();
}
return null;
}

public function PreviousArticle() {
$prev = DataObject::get("NewsArticle","NewsArticle.Date >= '{$this->Date}' AND NewsArticle.ID <> {$this->ID}","NewsArticle.Date.ASC, NewsArticle.ID DESC","","0,1");
if ($prev && $prev->exists()) {
return $prev->First();
}
return null;
}

We need to use '<=' and not '<' for checking the date in the 'NextArticle' function because two articles may have been posted on the same date and we don't want to skip over those. We need to exclude the current article from the list though, hence the 'NewsArticle.ID <> {$this->ID}' clause.

I'd also recommend escaping the bracket in your template code like this:

<% if PreviousArticle %>

<% control PreviousArticle %>

<a class="prev" href="$Link">&lt;</a>

<% end_control %>

<% end_if %>

<% if NextArticle %>

<% control NextArticle %>

<a class="next" href="$Link">&gt;</a>

<% end_control %>

<% end_if %>


Posted to: Prev/Next when ordered by DATE? | Show Thread | Post Reply


Viewing all articles
Browse latest Browse all 4235

Trending Articles