Skip to content

Instantly share code, notes, and snippets.

@kongondo
Forked from somatonic/image_tags.php
Created June 19, 2013 09:12
Show Gist options
  • Save kongondo/5812892 to your computer and use it in GitHub Desktop.
Save kongondo/5812892 to your computer and use it in GitHub Desktop.
Collect all tags from images field and create a link list to then filter pages with images that have the selected tag
<?php
/**
* collect all tags
* ======================================
*/
$alltags = array(); // container
// find all pages that have images with tags
$parray = $pages->find("template=basic-page|gallery, images.tags!=''");
// loop pages found and collect tags from images
foreach($parray as $p) {
// find all images that have no empty tags, yeah you can
// also use find on Pagefiles array!
$images = $p->images->find("tags!=''");
// loop them and add tags to array
foreach($images as $im) {
$tags = $im->tags;
// convert "," and "|" to space and create array using explode
if(strpos($tags, ',') !== false) $tags = str_replace(',', ' ', $tags);
if(strpos($tags, '|') !== false) $tags = str_replace('|', ' ', $tags);
$tags = explode(' ', strtolower($tags));
// merge new tags array to the container
$alltags = array_merge($alltags,$tags);
}
}
/**
* generate links with tags as urlsegment
* ======================================
*/
// make the array unique and create a tags nav from it
// add tags to the url of the page to later read it and
// render a list of pages
echo "<ul>";
foreach(array_unique($alltags) as $tag) echo "<li><a href='{$page->url}$tag'>$tag</a></li>";
echo "</ul>";
/**
* find all pages with the supplied tag
* ======================================
*/
// enable url segments on the template for this page
// to get the url segment from tag links
if($input->urlSegment1){
// sanitize the value
$tagvalue = $sanitizer->selectorValue($input->urlSegment1);
// find pages with images having the requested tag
$pa = $pages->find("images.tags~=$tagvalue");
if(count($pa)) {
echo "<h2>Pages found</h2>";
echo "<ul>";
foreach($pa as $p) echo "<li><a href='$p->url'>$p->title</a></li>";
echo "</ul>";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment