PHP foreach WordPress获取父类别名称和slug

时间:2015-08-31 16:01:41

标签: php wordpress foreach

我正在开发一个为特定类别集生成自定义面包屑的函数。

类别slugs存储在array()中,如下所示。

$specialCatsLvl2 = array('base-ball', 'soc-cer', 'foot-ball', 'hockey', 'basket-ball')  
// lets pretend these are the real slugs

我想编写一个foreach(){}循环,这样我就可以获得父类别,然后使用该父类别和slug作为面包屑中链接的变量。

这是我的。

if (is_product_category($specialCatsLvl2)) {

    foreach ($specialCatsLvl2 as $cat) {
    $parent = get_category($cat->category_parent);
    $parent_name = $parent->cat_name;
    }

echo $shop_link . $delimiter . '<a href="' . home_url() . '/product-category/' . $parent_name->slug . '/">' . $parent_name . '</a>' . $delimiter . $current_before . single_cat_title('', false) . $current_after; 

}

这是获取父产品类别的正确方法吗?

关于此事的任何意见或建议都会非常有帮助,我觉得我已经搜索过四个小时没有取得进展。

感谢您的阅读。

1 个答案:

答案 0 :(得分:1)

代码中的错误很少。首先,这个:$parent_name->slug不起作用。 $parent_name是一个字符串,您应该使用$parent->slug。其次,你向一个WooCommerce is_product_category函数发送一个slug数组,它需要一个字符串,而不是一个数组。第三,$cat->category_parent将不起作用,因为$cat是一个字符串,而不是一个类别对象。第四,在循环的每次迭代中$parent$parent_name都被覆盖。

我建议使用这个代码,用你的示例数组写一个像这样的面包屑(假设Sports是Soccer的父类):

  

主页&gt;体育&gt;足球

// Print the breadcrumb base
echo $shop_link . ' ' . $delimiter;

// If we're in a category that match your array
$current_category = get_category (get_query_var('cat'));
if(in_array($current_category->slug, $specialCatsLvl2) && $current_category->parent) {
    $parent = get_category($current_category->parent);
    // Print the parent category link
    echo '<a href="' . home_url() . '/product-category/' . $parent->slug .'/">' . $parent->name . '</a> ' . $delimiter;
}

 // Print the current category name
echo $delimiter . $current_before . single_cat_title('', false) . $current_after;