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

问题描述

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

我没有运气就尝试了很多解决方案。我已经设法实现了一个带有实际类别ID的代码,添加了+1和-1并且能够创建链接,但是最大的问题是,当“下一个链接”位于最后一个无法正常工作的类别时,不是链接的无限循环。 IE,如果我在第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>

解决方法

已更新:

您只需要定义您的第一个和最后一个类别ID。然后它将作为无限循环(假设您的产品类别术语是连续的)

<?php
if ( is_product_category() ) :
$taxonomy    = 'product_cat'; // WooCommerce product category taxonomy
$term_id     = get_queried_object_id(); // Current product category term Id

// Get first product category term Id
$query_args  = 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  = get_terms($query_args);
$term_id_end  = 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; 

$next_term_link = get_term_link( $next_term_id,$taxonomy );
$next_term      = get_term( $next_term_id,$taxonomy );

$prev_term_link = get_term_link( $prev_term_id,$taxonomy );
$prev_term      = 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; ?>

要获取最后一个类别,您可以尝试以下

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...