Hi @greencode
The code you use to populate $attachment_id
is OUTSIDE the sub categories loop. Therefor, it will not be dynamic for each category.
You need to move this within the loop.
You may find that the_category_ID
doesn’t work within the loop. You will need to use $category->term_id of something similar
Thanks
E