3

I have a category that I'm trying to load via a plugin. Looking at the categories service I see there is a function called "getCategoryById" but I don't know what the ID is so instead I'm loading the category group thinking that the ID provided there is what I need, apparently it is not.

Kinda of stumped on this one. Any advice?

Thanks,

  • Hey Matt - what infomormation do you have about the category? Name, level, slug? – Aaron Berkowitz Apr 20 '15 at 16:28
2

Depending on what you are searching by, you can use something similar to this. You can see the properties you can search by in the documentation.

$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->group = 'CategoryGroupName';
$criteria->title = 'CategoryTitle';
$criteria->limit = 1;

$category = $criteria->find();
| improve this answer | |
  • Doesn't craft()->elements->getCriteria(ElementType::Category); technically load all categories? If so I want to avoid the overhead. – Matt V Apr 20 '15 at 16:37
  • Nope! It loads an element criteria model of type Category. That simply allows you to query against Category properties like group, title, level, etc. (source) – Aaron Berkowitz Apr 20 '15 at 16:41
  • Oh ok. Cool. I'll give this a try. – Matt V Apr 20 '15 at 16:47
  • Question: How would I get only the children of a given category? What I mean is... I have a list of countries and under them their states/provinces. Is it possible to do something like $criteria->children = 1? I've tried this and it doesn't work. – Matt V Apr 28 '15 at 20:14
  • 1
    Yeah, you will need to first get the parent category, then get the children in two separate finds. If you are going to be running these steps frequently, I highly recommend cacheing the process. You can see a simple cache example in this service I made for the Craft CMS summit. – Aaron Berkowitz Apr 29 '15 at 15:02

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.