为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
一只萌萌小番薯 2023-10-15 14:48:27
我想自定义 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>
查看完整描述

1 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

更新:


您只需定义第一个和最后一个类别 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; ?>

要获得最后一个类别,您可以尝试以下操作


查看完整回答
反对 回复 2023-10-15
  • 1 回答
  • 0 关注
  • 53 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信