带有上一个和下一个学期链接的 WooCommerce 产品类别页面

我想自定义 WooCommerce 类别页面 (archive-product.php) 以显示当前产品类别,但我也想在页面中的某处创建指向上一个和下一个类别术语链接的上一个和下一个链接。


我尝试了很多解决方案但没有运气。我已经设法实现了一个采用实际类别 ID 的代码,我添加了 +1 和 -1,并且能够创建链接,但最大的问题是当“下一个链接”位于最后一个不起作用的类别时,不是链接的无限循环。即,如果我在第 6 页上,即我拥有的最后一个类别,下一个应该是 1,上一个应该是 5,如果我在第一个类别上,上一个应该是 6,下一个应该是 2。


请在下面找到我正在使用并且正在工作但不符合我需要的代码:


<?php

$taxonomy = 'product_cat';

$cate = get_queried_object();

$cateID = $cate->term_id;


$next_cateID = $cateID + 1;

$prev_cateID = $cateID - 1; 


$next_term_link = get_term_link( $next_cateID, $taxonomy );

$next_term = get_term( $next_cateID, $taxonomy );

$next_slug = $next_term->name;


$prev_term_link = get_term_link( $prev_cateID, $taxonomy );

$prev_term = get_term( $prev_cateID, $taxonomy );

$prev_slug = $prev_term->name;

?>


<p><a href="<?php echo $prev_term_link ?>"><?php echo $prev_slug; ?></a></p>

<p><a href="<?php echo $next_term_link ?>"><?php echo $next_slug; ?></a></p>


一只萌萌小番薯
浏览 60回答 1
1回答

翻阅古今

更新:您只需定义第一个和最后一个类别 ID。然后它将作为无限循环工作(假设您的产品类别术语是连续的):<?phpif ( is_product_category() ) :$taxonomy&nbsp; &nbsp; = 'product_cat'; // WooCommerce product category taxonomy$term_id&nbsp; &nbsp; &nbsp;= get_queried_object_id(); // Current product category term Id// Get first product category term Id$query_args&nbsp; = array('taxonomy' => 'product_cat', 'hide_empty' => false, 'orderby' => 'term_id', 'number' => '1', 'fields' => 'ids');$term_id_1st = get_terms($query_args);$term_id_1st = reset($term_id_1st);// Get last product category term Id$query_args['order'] = 'DESC';$term_id_end&nbsp; = get_terms($query_args);$term_id_end&nbsp; = reset($term_id_end);$next_term_id = $term_id_end == $term_id ? $term_id_1st : $term_id + 1;$prev_term_id = $term_id_1st == $term_id ? $term_id_end : $term_id - 1;&nbsp;$next_term_link = get_term_link( $next_term_id, $taxonomy );$next_term&nbsp; &nbsp; &nbsp; = get_term( $next_term_id, $taxonomy );$prev_term_link = get_term_link( $prev_term_id, $taxonomy );$prev_term&nbsp; &nbsp; &nbsp; = get_term( $prev_term_id, $taxonomy );?><p><a href="<?php echo $prev_term_link ?>"><?php echo $prev_term->name; ?></a></p><p><a href="<?php echo $next_term_link ?>"><?php echo $next_term->name; ?></a></p><?php endif; ?>要获得最后一个类别,您可以尝试以下操作
打开App,查看更多内容
随时随地看视频慕课网APP