I'm trying to create a loop that displays a list of the categories (as buttons) of a custom post type. I have a loop that works, but it is looping through all the custom posts and display each category. So right now if I have two posts with the same category, it will display that same category twice. Also I need to echo out custom classes for my isotope filter to work.
This is my code:
<?php
$args = array(
'post_type' => 'ondernemers',
'posts_per_page' => 10
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$categories = get_the_category( $post->ID, 'taxonomy' );
foreach( $categories as $category ) {
echo '<button class="button" data-filter=".' . $category->slug . ' "><div class="button-img-' . $category->slug . '"></div>' . $category->name . '</button>';
}
endwhile;
?>
Is there a way to make the loop print each category only once, instead of once for each time it is just for each unique post?
Use below code to retrieve category name of a custom post type.
<?php
$args = array(
'type' => 'post', /* custom post type name */
'parent' => '',
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'taxonomy' => 'category' /* custom post type texonomy name */
);
$cats = get_categories($args);
foreach ($cats as $cat) {
$cat_id= $cat->term_id;
$cat_name= $cat->name; ?>
<h3><?php echo '<a href="' . get_category_link( $cat_id ) . '">'.$cat->name.'</a>'; ?></h3>
<?php } ?>