Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

link to custom taxonomy by id

Through a series of specific requirements, I find myself needing to link to a custom taxonomy category using its term id...

I've got this - which displays a link to all taxonomies - I wish to change it so it only displays a link to the taxonomy with the term id dynamically pulled from a custom field I'm using.

$taxonomy = 'event-categories';
$terms = get_terms($taxonomy);
if ($terms) {
foreach($terms as $term) {
echo '<li><a href="http:/mysite.com/events/categories/project-events/' . $term->slug . '">' . $term->name .'</a></li>';
 }
};

essentiall I need "link_to_taxonomy_category(x)" where x = term_id

Thanks

like image 440
JorgeLuisBorges Avatar asked Dec 10 '22 01:12

JorgeLuisBorges


1 Answers

The function you are looking for is get_term_link. It takes either a term object, ID or slug and a taxonomy name and returns a URL to the term landing page.

As a side note hard coding the link as you have in the example above is fragile -- always keep your code as portable as possible. If the site is moved to a different domain, that link will break. WordPress has several functions that generate links dynamically based on the current installation environment. get_term_link is one example.

From the Codex:

$terms = get_terms('species');
echo '<ul>';
foreach ($terms as $term) {
    echo '<li><a href="'.get_term_link($term->slug, 'species').'">'.$term->name.'</a></li>';
}
echo '</ul>';
like image 141
gradyetc Avatar answered Dec 21 '22 17:12

gradyetc