在woocomerce类别页面中获取下一个和previuos类别链接

时间:2017-03-30 02:07:51

标签: wordpress categories product shop

我在woocmmerce中获取下一个和上一个类别链接和名称时遇到问题。 实际上我找到了this,但它仅用于正常的wordpress类别帖子.. 我需要下一个和上一个产品类别...任何帮助..我会知道

我尝试了以下代码,但这根本不符合逻辑......:

 global $wp_query;
// get the query object
$cat = $wp_query->get_queried_object();
$cateID = $cat->term_id -1;
$termname = get_term_by( 'id', $cateID, 'product_cat' );
$plinkname = get_term_link(  $cateID, 'product_cat' );

这将重新启动+1类别ID ..但例如,当其中一个类别被删除时,它将无效。

1 个答案:

答案 0 :(得分:0)

functions.php

{
"src": "Pictures/Comics/spi.jpg",
"descr": "Spider man is a nice comic The main spider-man comic ended with Peter Parker's death."
}

}

在主题文件中调用此函数:

function woocommerce_next_prev_link() {
if ( is_product_category() ){
    $taxonomy = 'product_cat';
    // Load all the terms for the product category
    $terms = get_terms( array(
        'taxonomy'   => $taxonomy,
        'hide_empty' => FALSE,
    ) );

    // Put all of the category id's into a simple array for searching
    $ids = array();
    foreach( $terms as $term ) {  
      $ids[] = $term->term_id; 
    }
    global $wp_query;
    $cat_obj = $wp_query->get_queried_object();

    // Load the current term ID from the current query
    $this_term = $cat_obj->term_id;
    // Find the term in the list of ID's

    $this_position = array_search( $this_term, $ids );
    // Identify the previous term
    $prev_position = $this_position - 1;
    // Identify the next term
    $next_position = $this_position + 1;

    // IF the previous term exists, and is not "off" the list (the currently displayed term is not the first term), then display the link
    if( $prev_position >=0 ) {
        $prev_id = array_slice( $ids, $prev_position, 1 );
        $prev_term = get_term( $prev_id[0], $taxonomy );
        if ( $prev_term ) {
            echo '<a href="' . get_term_link( $prev_term->term_id, $taxonomy ) . '">&laquo; ' . $prev_term->name . '</a>'; 
        }
    }

     // IF the next term exists, and is not "off" the list (the currently displayed term is not the last term), then display the link
    if( $next_position > 0 && $next_position < count($ids) ) {
        $next_id = array_slice( $ids, $next_position, 1 );
        $next_term = get_term ($next_id[0], $taxonomy );
        if ( $next_term ) {
            echo '<a href="' . get_term_link( $next_term->term_id, $taxonomy ) . '">' . $next_term->name . ' &raquo;</a>'; 
        }
    }
}