How to get term name with link for specific ids

I am trying to display custom category on archive page.

$term_id_array= array(1,2,4,50);

how to retrieve the term name with link for these term_ids

My custom post_type name = product
taxonomy = product_cat

Note: I am using woocommerce.

Please help I am trying this code to display all product category name as a list

<?php 
$taxonomy = 'product_cat'; //Choose the taxonomy
$terms = get_terms( $taxonomy ); //Get all the terms
foreach ($terms as $term) { //Cycle through terms, one at a time
$term_id = $term->term_id; //Define the term ID
$term_link = get_term_link( $term, $taxonomy ); 
$term_name = $term->name;
echo '<p class="list-cat"><span>' . $term_id . '</span> -<span>' . $term_name . '</span></p>';  
}
?>

Out put:

1- Clothing
2- Shirt
3- Pant
4- Lady’s Pant
5- T-shirt
6……..
…….
5- Sun Glass

But How can I get Name with link for this 1,2,4,50 IDs.

1 Answer
1

get_terms() accept an array of arguments as second parameter. One of those parameters are include

include

(integer) An array of term ids to include. Empty returns all.

You already have your selected term ids in an array, so just simply pass them to the include parameter in the array of arguments in get_terms()

$terms =  get_terms( $taxonomy, array( 'include' => $term_id_array ) );

or with short araay syntax (availble since PHP 5.4)

$terms = get_terms( $taxonomy, ['include' => $term_id_array] );

Leave a Comment