簡體   English   中英

WooCommerce 產品類別頁面,帶有上一期和下一期鏈接

[英]WooCommerce product category pages with previous and next term links

我想自定義 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; ?>

要獲得最后一個類別,您可以嘗試以下操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM