php - 返回不在父项中的子类别
问题描述
我在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', '←', TRUE, ' ', 'product_cat');
$next = previous_post_link('%link', '→', TRUE, ' ', 'product_cat');
echo $previous;
echo $next;
echo '</div>';
}
解决方案
您可以使用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
}
通过使用此代码,您可以提取:
- 孩子
- 子父级
- 家长
希望能帮助到你!:)
推荐阅读
- continuous-integration - Gitlab自托管:错误:将工件作为“存档”上传到协调员......存档太大
- javascript - 从外部 url 获取 JSON 数据并将其打印为 HTML
- java - 如何在 android 的另一个 RecyclerView 中将 RecyclerView(从 API 获取的数据)显示为列表项?
- html - 试图在中间有一个带有可滚动内容的左右*响应*侧边栏,滚动条在右侧
- excel - Excel:使用具有多个结果的多个条件进行搜索
- c++ - 在C++中,当模板参数没有出现在下面的类或函数声明中时,它有什么用?
- oracle - 我们可以在 oracle 中找到外部表的 ddl 脚本(任何系统表)
- c - 在 C 输入重定向问题中实现 shell
- java - 在当前主题中找不到“@attr/textappearancebutton”
- linux - 通过递增值和乘法进行文本操作