I’m trying to create a ‘categories’ page which displays all of my categories along with an image for that category. Instead of this page being static I want to pull through the most recent posts featured image for that category and use that as the category image.
My code below kind of works, it pulls through the most recent featured image but it doesn’t appear to be category specific (it’s just pulling through the most recent.
Just to clarify I am using a custom post type and a custom taxonomy:
Post Type: gallery
Taxonomy: categories
<?php
$limit = 999;
$counter = 0;
$cats = get_terms([
'taxonomy' => 'categories',
'hide_empty' => false,
]);
foreach ($cats as $cat):
if ($counter < $limit) {
$args = array(
'posts_per_page' => 1,
'post_type' => 'gallery',
'taxonomy' => 'categories',
'cat' => $cat->cat_ID,
'ignore_sticky_posts' => 1
);
$posts = get_posts($args);
if ($posts) {
echo '<div class="col-md-3 category-list">';
while( have_posts() ) : the_post();
echo '<a href="' . get_category_link($cat->term_id) . '" ' . '><div class="cat-list-img">';
the_post_thumbnail();
echo '<h5 class="cl-title">' . $cat->name . '</h5>';
echo '</div></a>';
echo '</div>';
endwhile;
}
}
$counter++;
endforeach;
?>
Since some of the posts share the same category, it would be great if I could avoid each using the same post and instead take the image from the next post (rather than duplicating), but I’m not sure how to do this so haven’t even attempted – if it’s easier than it sounds it would be great if you could also point me in the right direction for this.
2
Answers
Without having your post type or taxonomy, it’s difficult to test whether or not this works. However, this should work.
As stated in the comments, you need to use get_the_ID() and I would also think that you need the
get_term_link
function rather thanget_category_link
as that would be for apost
taxonomycategory
being the default WordPress category taxonomy.To avoid duplicates, you can store the displayed post ID in an array and bypass if it appears again from other categories queries.