Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Template Questions

Getting Random Children


2 Posts   646 Views


19 July 2012 at 9:22am Community Member, 3 Posts

I'm trying to retrieve random children of a product group page. I can retrieve the product group page from teh template, but I can't call any more custom functions. currently in my Page.php I'm using

function RandomChildren($count = 2)
$pages = DataObject::get("SiteTree","ParentID = $this->ID","RAND()",null,$count);
return $pages;


And to call in the template I'm using

<% control RandomChildren(2) %>
<% end_control %>

But the Debug isn't even showing, and I'm in "Dev" mode

I've tried other methods, and also found that at one point, if I retrieve a page using

return DataObject::get('SiteTree','ParentID = $this->ID);

I will debug and see the results of the object as expected,

but when I use this to get random children it fails, if i debug the ID of the object, it's empty

$page = DataObject::get('SiteTree','ParentID = $this->ID)

This site is very complicated, but the logistics should work. I've used this code before on other projects, and have never seen this problem, any thoughts anyone???


4 November 2012 at 3:36am (Last edited: 4 November 2012 3:38am), Community Member, 9 Posts

What version of SS are your using?

You could do something like this:

function RandomChildren($count = 2) {
   return SiteTree::get()->filter('ParentID', $this->ID)->sort('RAND()')->limit($count);

I gave this a quick try and it works fine. Hope this works for you!