<?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
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
$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
}
Then Better to use....
if(strcmp($tag , $tagToFind))
{
echo "Found";
}
else
{
echo "Not found";
}
may this works for you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.