[英]Filter custom post type archive with product category
我有一個基於 Woocommerce 產品分類的自定義帖子類型。 我想使用這些分類法來過濾存檔頁面上的自定義帖子。
我已經閱讀了很多關於此的文章,但無法實現我的目標。 到目前為止,我已經創建了一個新的 archive-mypost.php 頁面,並使用以下代碼顯示了所有海關帖子和所有類別:
<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>
但是過濾器不起作用,當我點擊一個類別時沒有任何反應。 此外,我仍在嘗試弄清楚如何僅顯示帶有結果的類別並隱藏其余類別。
感謝大家 !
我已經找到了解決方案的一部分此代碼可用於在自定義帖子存檔頁面上顯示 woocommerce 類別並過濾結果。
我唯一不知道的是首先僅顯示頂級類別,然后選擇頂級類別時,顯示子類別
<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>
在我的 function.php 頁面中:
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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.