• Hello,

    In the posts loop, which contains each ( post ) one or multiple categories, i would like to get the ID of a category contains a certain word.

    For example, a post is in category “Red Car”, “Blue Car”, “Yellow Car”. I would like to get the id of the category containing the word “Red”, ie “Red Car” in the posts loop.

    Or the id of the category “Truck Red” in another post loop.

    Thanks for your help.

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Use get_the_category() to get the current post’s category terms in an array. Despite the singular form of the function name, it does return all category terms assigned to the post. Loop through the terms and search each name field for the target word. Any time there’s a match, you could add the related ID to an array. When the term loop concludes you will have an array of term IDs where the target word exists.

    If you truly need word matches and not string matches, consider using preg_match() to search so you can use a regexp to extract only full words. Consider the phrase “WordPress words are the word”. If you just searched for the string “word” (case insensitive), there’d be 3 matches. If you did a regexp search for the word “word”, it would only match once. If desired, regexps can match either “word” or “words” but not “WordPress”. Regexp is very powerful and flexible, though difficult to construct.

    Their other drawback is they take much more processing power. If you have many posts that need their terms searched, using preg_match() will slow down the process. Regexp should be avoided when possible for this reason.

Viewing 1 replies (of 1 total)
  • The topic ‘Get the id of a category containing a certain word’ is closed to new replies.