这是我在开始这篇文章之前尝试的一个很长的解决方案。希望这能帮助别人更好地理解。
<?php
// Get list of all taxonomy terms -- In simple categories title
$args = array(
\'taxonomy\' => \'project_category\',
\'orderby\' => \'name\',
\'order\' => \'ASC\'
);
$cats = get_categories($args);
// For every Terms of custom taxonomy get their posts by term_id
foreach($cats as $cat) {
?>
<a href="<?php echo get_category_link( $cat->term_id ) ?>">
<?php echo $cat->name; ?> <br>
<?php // echo $cat->term_id; ?> <br>
</a>
<?php
// Query Arguments
$args = array(
\'post_type\' => \'portfolio\', // the post type
\'tax_query\' => array(
array(
\'taxonomy\' => \'project_category\', // the custom vocabulary
\'field\' => \'term_id\', // term_id, slug or name (Define by what you want to search the below term)
\'terms\' => $cat->term_id, // provide the term slugs
),
),
);
// The query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo \'<h2> List of posts tagged with this tag </h2>\';
echo \'<ul>\';
$html_list_items = \'\';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$html_list_items .= \'<li>\';
$html_list_items .= \'<a href="\' . get_permalink() . \'">\';
$html_list_items .= get_the_title();
$html_list_items .= \'</a>\';
$html_list_items .= \'</li>\';
}
echo $html_list_items;
echo \'</ul>\';
} else {
// no posts found
}
wp_reset_postdata(); // reset global $post;
?>
<?php } ?>