You can start with get_terms() to get the topic terms. This can be wrapped in a helper function so that you don't have to specify the parameters every time you use get_terms()
. Additionally with the helper function you can force the return value to always be an array. E.g.
function my_resources_topic_terms() {
$topics = get_terms( array(
'taxonomy' => 'resources_topics',
'hide_empty' => true,
) );
return is_array( $topics ) ? $topics : [];
}
As bosco pointed out in the comments use get_posts()
or new WP_Query()
to retrieve posts. You'lle need to use tax_query
parameter to limit the query to specific term(s). The query can also be wrapped in a helper function to make it reusable and to utilise default parameters. E.g.
function my_resources_posts_by_topic( WP_Term $topic ) {
$query = new WP_Query([
'post_type' => 'resources',
'post_status' => 'publish',
'posts_per_page' => 3,
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'tax_query' => [
[
'taxonomy' => 'resources_topics',
'field' => 'term_id',
'terms' => $topic->term_id,
]
],
]);
return $query->posts;
}
Then it is just a matter of looping a loop to get the terms and posts associated with them. Use the WP functions to retrieve the post links (get_permalink()) and the term archive link (get_term_link()). Term (WP_Term) and post (WP_Post) details, such as titles, are public class properties and can be accessed directly with ->
. E.g.
foreach ( my_resources_topic_terms() as $topic_term ) {
echo '<div class="topic">';
printf(
'<h2 class="topic__title">%s</h2>',
esc_html( $topic_term->name )
);
printf(
'<ul class="topic__posts">%s</ul>',
implode(
'',
array_map(
function( WP_Post $topic_post ) {
return sprintf(
'<li class="topic__post">
<a href="%s">%s</a>
</li>',
esc_url( get_permalink( $topic_post ) ),
esc_html( $topic_post->post_title )
);
},
my_resources_posts_by_topic( $topic_term )
)
)
);
printf(
'<a class="topic__more" href="%s">%s</a>',
esc_url( get_term_link( $topic_term ) ),
esc_html__( 'See More', 'textdomain' )
);
echo '</div>';
}
Do note that, if you have a great number of topics, then you might experience some performance issues with the resulting multiple queries. You may want to consider caching the query results for example in a transient and using some page caching mechanism.
get_posts()
or a newWP_Query
instance. Refer to theWP_Query
documentation for the keys/values accepted into either's argument as an associative array. If you make an attempt and get stuck, share the code you have and we can help you out from there.