0
<?php // SEARCH TAGS FOR A SPECIFIC TAG
  $tags = CollectionAttributeKey::getByHandle('recipe_tags'); // attribute handle of tags to search
  $tagToFind = 'Videos'; // declare the specific tag to find
  $selectedTags = array($page->getAttribute($tags->getAttributeKeyHandle())); // get tags associated with each page and put them in an array

  foreach ($selectedTags as $tag) { // output tags separately

    echo $tag; // ECHO TEST - check that individual tags associated with each page are outputting correctly

    if ($tag == $tagToFind) { // if $tag is equal to $tagToFind
      echo ' Found';
    } else {
      echo ' Not found';
      }
  }
?>

echo $tag; outputs the list of tags associated with each page so I'm pretty sure the issue is how I'm checking if 'Videos' is in the list of tags.

The above outputs the following list: Breakfast Brunch Budget Meal Easy Lunch Quick Meals Supper Vegetarian Videos and Not found even though Videos is in the list.

I've also tried using in_array to look for 'Videos' like this:

if (in_array($tagToFind, $selectedTags, true)) { // search the array for $tagToFind - true = strict
  echo ' Found';
} else { 
    echo ' Not found';
  }

But get the same result - I'm new to php so sorry if this is easy.

Any help would be much appreciated.

Cheers

0

3 Answers 3

3

It seems that $selectedTags an array of one string, since your foreach only loops once

You should try doing

$selectedTags = explode(" ",$page->getAttribute($tags->getAttributeKeyHandle()));

Then use in_array function

Sign up to request clarification or add additional context in comments.

Comments

0
$page->getAttribute($tags->getAttributeKeyHandle()) 

seems to return a string.

In that case

$selectedTags = array($page->getAttribute($tags->getAttributeKeyHandle())); 

makes no sense - you get an array containing one long string.

What you want to to is:

$selectedTags = $page->getAttribute($tags->getAttributeKeyHandle());

if(stristr($selectedTags, $tagToFind)){
  // do something
}
else{
  // do something else
}

1 Comment

Awesome - easy when you know how!
0

Then Better to use....

if(strcmp($tag , $tagToFind))
{
    echo "Found";
}
else
{
    echo "Not found";
}

may this works for you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.