Jump to content

Working with tags


Recommended Posts


I'm created a site where it will have related case studies depending on the tags. I've got it working and it works perfectly, but I was just wondering if there was a more elegant approach using more of ProcessWires powerful API. 

So I have a page called Tags that are hidden, with the children being the tags themselves. On each Case Study I have a Tag field that is selectable from the Tags page. 

Then in my code I have:

foreach($page->tags as $tag) {
     $a[] = $tag->title; 
$a = implode("|", $q);
$results = $pages->find("tags~=$a")->shuffle();
foreach($results as $result) {
     if($page->id != $result->id) {
         echo "<a href='$result->url'><h1>$result->title</h1></a>";

Let me know if there is a more elegant way of doing this. I'm obsessed with clean code :(



Link to comment
Share on other sites

Looks fine to me. If you are obsessed with clean code you should read up on the api, there is tons of stuff that will save you some lines. For instance your couple lines could be blitzed with one little line of code. 


//no need to loop the results to an array if that is what you want

$query = $page->tags->implode("|","id");
$results = $pages->find("tags=$query")->shuffle(); 
Link to comment
Share on other sites

Also, you can remove the current page from the array to avoid the IF check inside the loop

$results = $pages->find("tags={$page->tags}")->remove($page)->shuffle();

Or, do the same as above with one less method:

$results = $pages->find("id!={$page},tags={$page->tags}")->shuffle();
Edited by diogo
added second method
  • Like 6
Link to comment
Share on other sites

Diogo, you are amazing! Thank you very much. ProcessWire is so beautiful. Remove doesn't seem to be on the Cheatsheet. There has been quite a few times people have suggested using things, that aren't on the Cheatsheet. I would love to see the Cheatsheet updated eventually. 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...