In my WordPress project, I have several different custom post types
and they all share a common taxonomy. I am in the final stage of the project and now is time to link all custom post types using a sidebar widget. The problem I am having is that I don’t know the appropriate way to get the term link
linked to the correct custom post type.
For example, I have custom post types: book, author, product; and a taxonomy: genre that includes a horror category.
I would like to be able to get link structure as such:
/book/genre/horror
/product/genre/horror
/author/genre/horror
When I do get_term_link('horror');
, I get one of the term links, it seems that one of the custom post type has preference. How can I manage to get each term link corresponding to the correct custom post type?
Hard coding it is never a good idea, so I was wondering if there is a proper way to go about this. This is an old issue I am having, and have done a lot of searching for a solution but I didn’t find it. I come here as the last resort. Thanks.
2 Answers
This code display all posts of all categories of genre taxonomy for custom post type book. Now, For different custom post type (author, product ) you have to change Custom Post Type Name inside $arg of WP_Query(). You will get term link using get_term_link($catterm) function or you can use also get_the_term_list().
$args = array(
'number' => $number,
'hide_empty' => $hide_empty,
'include' => $ids
);
$custom_categories = get_terms( 'genre ', $args );
foreach ( $custom_categories as $catterm){
$arg = Array(
'post_type' => 'book',
'posts_per_page' => '-1',
'post_status' => 'publish',
'tax_query' => Array( Array (
'taxonomy' => 'genre ' ,
'terms' => $catterm->term_id
)) );
$loop = new WP_Query( $arg );
global $post;
while ( $loop->have_posts() ) : $loop->the_post();
?>
<div class="gallery-content">
<div class="entry-content">
<?php
echo '<li>' . get_the_title() . '</li>';
echo '<li><a href="'.get_term_link($catterm).'">'.$catterm->name.'</a></li>';
?>
</div>
</div>
<?php endwhile;
}
?>