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 !
I have figured part of the solution This code works to display woocommerce categories on custom post archive page and filter results.
Only thing I do not know yet is to display only top categories first, then when the top category is selected, show subcategories
<div class="filter-custom-taxonomy">
<?php
$terms = get_terms( ['taxonomy' => 'product_cat'] );
foreach ( $terms as $term ) : ?>
<a href="<?php echo home_url() ?>/tutos/?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>
And in my function.php page :
function kbites_words_filter_archive( $query ) {
if ( ! $query->is_main_query() )
return $query;
if ( is_admin() ) {
return;
}
if ( is_post_type_archive('tutos') ) {
if (isset($_GET['getby'])) {
if ( 'cat' === $_GET['getby'] ) {
$taxquery = array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $_GET['cat'],
),
);
$query->set( 'tax_query', $taxquery );
}
}
$query->set( 'posts_per_page', 30 );
}
return $query;
}
add_action( 'pre_get_posts', 'kbites_words_filter_archive');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.