使用ProcessWire选择随机页面图像


Select Random Page Image with ProcessWire

我刚刚开始使用ProcessWire系统,并且非常喜欢它。

在我的主页上,我想显示来自随机页面的图像。该页面可以是任何页面,只要它是ID为'1010'的父页面的子页面。

这是可能的吗?如果是,我如何实现这一点?

显示主页图像的当前代码是这样的:if($page->image) echo "<img src='{$page->image->url}'>";但是,我想从上述父ID的任何子页面中选择一个随机图像。

我发现了这个,但不确定它是否有任何用处。

非常感谢您的指点:-)

您应该在模板代码中尝试这样做(假设您的图像字段称为image):

/* Find all children of page with ID 1010 that include an image */
$allChildPages = $pages->find('parent=1010,image.count>0');
/* Select a page from all children in the PageArray randomly */
$randomChildPage = $allChildPages->getRandom();
if ($randomChildPage->image) {
    echo "<img src='{$randomChildPage->image->url}'>";
}

查看相关代码:

  • $pages -> find()返回一个页面的集合(匹配的选择器)作为PageArray(扩展WireArray类)。
  • $anyWireArray -> getRandom()返回一个自身的随机元素

也可以看看这个论坛的帖子,里面讨论了几种从不同页面随机化图像的策略。