I have a custom post type based on Woocommerce product taxonomy. I would like to use these taxonomies to filter custom posts on the archive page.
I have read a lot of articles on this but could not achieve my goal.
So far I have created a new archive-mypost.php page and displayed all the customs posts and all the categories with the following code :
<div class="filter-custom-taxonomy">
<?php
$terms = get_terms( ['taxonomy' => 'product_cat'] );
foreach ( $terms as $term ) : ?>
<a href="?getby=cat&cat=<?php echo esc_attr( $term->slug ); ?>">
<?php echo esc_html( $term->name ); ?>
</a>
<?php endforeach; ?>
</div>
<div class="row">
<div class="small-12 columns">
<?php do_action( 'thb_archive_title' ); ?>
<div class="row">
<?php
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
get_template_part( 'inc/templates/post-styles/post-style1' );
endwhile;
endif;
?>
</div>
<?php
the_posts_pagination(
array(
'prev_text' => '',
'next_text' => '',
'mid_size' => 2,
)
);
?>
</div>
</div>
But the filter does not work, when I click on a categories nothing happens.
Also I am still trying to figure out how to show only categories with results and hide the rest.
Thanks everyone !
My Answer:
php
get_header();
$args = array(
'post_type' => 'mypost',
'posts_per_page' => -1
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
?>
}
}
wp_reset_postdata();
$terms = get_terms(array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
));
foreach ($terms as $term) {
?>
name; ?>
}
get_footer();
?>
_This code will display all the custom posts and all the product categories on the archive page. Now, to filter the custom posts based on the selected category, you can modify the `$args` array to include the selected category ID:_
php
$category_id = get_queried_object_id();
$args = array(
'post_type' => 'mypost',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $category_id
)
)
);
_With this modification, the custom posts will be filtered based on the selected product category. You can further customize the display of the filtered posts as needed._
Rate this post
4 of 5 based on 9177 votesComments