Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this questionI want to create on my blog a category loop with the featured image. But i don't know how i do that technical.
You should only see a list of categories and click on them to get the category site. It's like a article loop only with categories.
Thank you for any help :)
Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this questionI want to create on my blog a category loop with the featured image. But i don't know how i do that technical.
You should only see a list of categories and click on them to get the category site. It's like a article loop only with categories.
Thank you for any help :)
Share Improve this question asked Jan 14, 2019 at 17:49 Mr Sag ich nichtMr Sag ich nicht 111 silver badge2 bronze badges2 Answers
Reset to default 1Well, in WP the word "loop" is mainly related to posts. It's easier to say that you want to display categories.
All you have to do is to get them using get_categories
function and display them.
<?php
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC'
) );
if ( ! empty( $categories ) ) :
?>
<ul>
<?php foreach ( $categories as $category ) : ?>
<li><a href="<?php echo esc_attr(get_category_link( $category->term_id ) ); ?>"><?php echo esc_html( $category->name ); ?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
And if you want to change the category title to some ACF custom field, then change this part:
<?php echo esc_html( $category->name ); ?>
to:
<?php echo wp_get_attachment_image( get_field('<FIELD_NAME>', $category), 'full' ); ?>
PS. Remember to change to real name of the field. It should return the ID of an image (and not the array - you should set it in field setting). You can also change the 'full' size to some other size.
The key to this is get_categories()
function.
You can use it as follows, note that I assumed the featured image url is stored in a meta of the category which may not be your case:
$categories = get_categories();
if(count($categories)) {
foreach($categories as $cat) {
$catID = $cat->term_id;
$img = get_term_meta($catID, 'featured_image', true);
$url = esc_url( get_category_link( $catID ) );
echo "<a href='$url'><img src='$img' /></a>";
}
} else {
echo "No categories!";
}
In case you're using ACF image field to add the featured image to the category, it's better to use get_field('featured_image', 'category_'.$catID)
instead of get_term_meta()
. The code in that case depends on your field settings, so I encourage you to read the documentation here.