Skip to content
Advertisement

How to get just the term_ids from get_the_terms in WordPress

I am building a wordpress website that uses a custom AJAX filter that is linked to my Custom categories.

This is my function ajax-filter.php:

JavaScript

My question is:

How can i use my data from tax to term-id in the way that i use in my ajax-filter.php? to use my data ($value->title)

JavaScript

Advertisement

Answer

Firstly, well done on creating a Minimal example of your code, it makes it easier for us to see the problem and how to help 🙂

Now to your question:

There are 2 issues before you even get to your actual question

  1. get_the_terms only takes 2 parameters – you don’t need to pass ni the 3rd parameter $id. The id is passed in the 1st parameter already
  2. get_the_terms returns an array because a post can have multiple terms associated with it. You will need to consider how to handle multiple terms.

Handle a single term per post

For now, I’m going to assume you are only going to have a single term associated with the post, or if there are more only return the first.

Update your code as follows – the explanation for what is doing is in the comments:

JavaScript

This will all it to your $results array as follows: Array ( [0] => Array ( [title] => title [tax] => 54 ) )

Now you can access the term id in your loop like this $value->tax, e.g.

JavaScript

Handle Multiple terms per post

If you wanted to handle multiple terms, you could push the $term_ids array:

JavaScript

… and then loop through the array when you retrieve them:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement