首页 > 解决方案 > 返回不在父项中的子类别

问题描述

我在functions.php文件中添加了一个函数,所以当用户点击一个按钮时,用户会返回到所属产品的上一个分类页面,即使它是否在子分类中。

问题是,在我当前的函数中,当我导航到产品时,该函数将我返回到父类别,而不是子类别。

- Category
  |-> Sub Category
     |-> Product

功能

function previous_next_product(){

    echo '<div class="prev_next_buttons">';

    // Get parent product categories on single product pages
    $terms = wp_get_post_terms( get_the_id(), 'product_cat', array( 'include_children' => true ) );

    // Get the first main product category (not a child one)
    $term = reset($terms);
    $term_link =  get_term_link( $term->term_id, 'product_cat' ); // The link
    echo '<a href="'.$term_link.'"><i class="fa fa-bars" aria-hidden="true"></i></a>';

   // 'product_cat' will make sure to return next/prev from current category
   $previous = next_post_link('%link', '&larr;', TRUE, ' ', 'product_cat');
   $next = previous_post_link('%link', '&rarr;', TRUE, ' ', 'product_cat');

   echo $previous;
   echo $next;

   echo '</div>';

}

标签: phpwordpress

解决方案


您可以使用get_category获取类别对象,并且可以轻松提取slug或任何其他需要的信息。

这是示例代码:

//load data of your child category
$child = get_category(CHILD_CATEGORY_ID_HERE);

//from your child category, load sub parent object
$sub_parent = get_category($child->parent);

//load parent from your sub parent
$parent = get_category($sub_parent->parent);

//extract slug like this
echo $sub_parent->slug; //will print slug of sub parent

并检查,如果category有父母,你可以使用这个:

if($child->parent){
   //extract subchild slug here
   //can do similar check for parent, if exists then extract parent object info
}

通过使用此代码,您可以提取

  1. 孩子
  2. 子父级
  3. 家长

希望能帮助到你!:)


推荐阅读