WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following code and I want to use the term_id inside that function. I aware that the variable $terms contains the term; however, I do not know how to get the term id from it.


function wpse5123_set_object_terms($object_id, $terms, $tt_ids, $taxonomy){
       if($taxonomy == 'category'){
           echo '<pre>';

I tried the following but it does not work:

foreach (  $terms as $term) {
    $term_id[] = $term->term_id;    
share|improve this question
Your own code should be sufficient to demonstrate that $terms isn't an object. It is, in fact already the array of IDs that you are trying to generate. If that is the only problem, you don't really have a problem. – s_ha_dum Mar 19 '14 at 2:29
@s_ha_dum $terms should have the id, but it doesnt. How can I get the id from $terms? – Gixty Mar 19 '14 at 3:22
@Gixty $terms is exactly what you passed as 2nd argument to wp_set_object_terms (or wp_set_post_terms). If you passed to that function an array of term slugs, than you have to use get_term_by to get term objects and then term ids from objects. If you pass an array of ids, then you already have the ids... If you pass a single value $terms will be an array of one element (an id if you passed and id, a slug if you passed a slug). – gmazzap Mar 19 '14 at 5:11
@G.M. Thank you. However, when I add a term, the $terms contains the term id, but when I remove it, $terms is empty. So, if it's empty, I cannot use it. How can I get the term id when removing it? – Gixty Mar 19 '14 at 14:01

I finally found the solution to delete all the postmeta related to the term being deleted.

For this, we need to use the action hook 'delete_term_taxonomy' because it is executed before the term is deleted; therefore, we can find the term object and use it inside the hook.

Then, we proceed to perform certain task such as deleting all postmeta related to the term.

Here is the code:

add_action( 'delete_term_taxonomy', function($tt_id) {

    $taxonomy = 'category';    
    $term = get_term_by('term_taxonomy_id', $tt_id, $taxonomy); 
    $user_name = $term->name;
    $meta_key = "_category_relation_added_" . $user_name;
    delete_post_meta_by_key( $meta_key );

}, 9, 1);
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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