How to get the current taxonomy term ID (not the slug) in WordPress?

291,216

Solution 1

Nevermind! I found it :)

get_queried_object()->term_id;

Solution 2

Simple and easy!

get_queried_object_id()

Solution 3

Here's the whole code snippet needed:

$queried_object = get_queried_object();
$term_id = $queried_object->term_id;

Solution 4

Use following code

This will print your current taxonomy name and description(optional)

<?php 
   $tax = $wp_query->get_queried_object();
   echo ''. $tax->name . '';
   echo "<br>";
   echo ''. $tax->description .''; 
?>

Solution 5

If you are in taxonomy page.

That's how you get all details about the taxonomy.

get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

This is how you get the taxonomy id

$termId = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) )->term_id;

But if you are in post page (taxomony -> child)

$terms = wp_get_object_terms( get_queried_object_id(), 'taxonomy-name');
$term_id = $terms[0]->term_id;
Share:
291,216
InvalidSyntax
Author by

InvalidSyntax

Updated on July 08, 2022

Comments

  • InvalidSyntax
    InvalidSyntax almost 2 years

    I've created a taxonomy.php page in my WordPress theme folder. I would like to get the current term id for a function. How can I get this?

    get_query_var('taxonomy') only returns the term slug, I want the ID

  • David
    David about 9 years
    You could also just use get_queried_object_id() to retrieve just the ID. Whole snippet would be $term_id = get_queried_object_id();
  • Admin
    Admin over 8 years
    Good answer . Recently i see an question in WordPress stack exchange . Could you please check . wordpress.stackexchange.com/questions/214453/…
  • Pea
    Pea over 5 years
    get_queried_object_id() was introduced in 3.1.0 (February 23, 2011) and should be the correct answer for the question asked. > taxonomy.php page in my wordpress template folder, I would like to get the current term id for a function.
  • Fury
    Fury over 5 years
    Bear in mind this will work only in taxonomy page. But if you in taxonomy child page you won't get the taxonomy id.