4

Ok I can do this in twig but after searching high and low I can't find a good example of how to do it in a plugin.

I have a user profile field called interests which holds an array of what they are interested in. I want to pull out all entries that are related to the category id's held in the interests array. So in twig I do this:

{% for interest in userinterests %}
    {% for entry in entries.relatedTo(craft.categories(interest)) %}
        <li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
    {% endfor %}           
{% endfor %}

In my plugin function I currently have this but it is not returning anything in the array so I'm currently stuck:

$userinterests = craft()->users->getUserById($userid)->getContent()->getAttributes();
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->relatedTo = array(
    'sourceElement' => $categories
);
$relatedEntries = craft()->elements->findElements($criteria);

I'm not sure what I am supposed to be adding to the relatedTo array but it also could be something else as I'm still trying to get my head around craft.

Any help much appreciated.

  • Hi Lettie. What is $categories being set to? – Aaron Berkowitz Apr 30 '15 at 18:08
  • That's kind of what I need to find out. It's not doing anything at the moment. What I want it to do is hold an array of id's of the userinterests and pull out any entries which have the id as a category in the entires table. Each entry can have multiple categories so may get pulled out more than once but I can deal with that once I get the entries returned that I want to work with. Cheers. – Lettie Apr 30 '15 at 19:27
2

Ok worked this one out eventually myself. If anyone else finds this helpful.

$userinterests = craft()->users->getUserById($userid)->getContent()->getAttributes();
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->relatedTo = array(
        'targetElement' => $userinterests['relevantFieldToCheckAgainst'],
        'field' => 'EntryFieldToCheckIn'
);
$relatedEntries = craft()->elements->findElements($criteria);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.