How do I get current taxonomy term id on wordpress

2019-03-07 19:16发布

I've created a taxonomy.php page in my wordpress template 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

8条回答
疯言疯语
2楼-- · 2019-03-07 19:29

Simple and easy!

get_queried_object_id()
查看更多
够拽才男人
3楼-- · 2019-03-07 19:31

Just copy paste below 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 .''; 
?>
查看更多
虎瘦雄心在
4楼-- · 2019-03-07 19:32

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;
查看更多
\"骚年 ilove
5楼-- · 2019-03-07 19:33

See wp_get_post_terms(), you'd do something like so:

global $post;
$terms = wp_get_post_terms( $post->ID, 'YOUR_TAXONOMY_NAME',array('fields' => 'ids') );

print_r($terms);
查看更多
在下西门庆
6楼-- · 2019-03-07 19:35

Here's the whole code snippet needed:

$queried_object = get_queried_object();
$term_id = $queried_object->term_id;
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-03-07 19:36

It's the term slug you want.Looks like you can get the id like this if that's what you need:

function get_term_link( $term, $taxonomy = '' ) {
    global $wp_rewrite;

    if ( !is_object($term) ) {
        if ( is_int( $term ) ) {
            $term = get_term( $term, $taxonomy );
        } else {
            $term = get_term_by( 'slug', $term, $taxonomy );
        }
    }
查看更多
登录 后发表回答