wordpress get post taxonomy terms code example

Example 1: get posts from selected taxonomy

$posts_array = get_posts(
    array(
        'posts_per_page' => -1,
        'post_type' => 'fabric_building',
        'tax_query' => array(
            array(
                'taxonomy' => 'fabric_building_types',
                'field' => 'term_id',
                'terms' => $cat->term_id,
            )
        )
    )
);

Example 2: wordpress get taxonomy of a post

<?php $term_obj_list = get_the_terms( $post->ID, 'taxonomy_name' ); ?>

Example 3: get taxonomy name in singhle post

// RETRIVE TERM SLUG ( for single.php or template-part )

$terms = get_the_terms( $post->ID, 'your-taxonomy' );
if ( !empty( $terms ) ){
    // get the first term
    $term = array_shift( $terms );
    echo $term->slug;
}

Example 4: get term id by post id

INSIDE TAXONOMY PAGES
$term      = get_queried_object();
$term_id   = $term->term_id;

Tags:

Php Example