RobBenz
RobBenz

Reputation: 609

PHP foreach WordPress get parent category name and slug

I am working on a function that produces custom breadcrumbs for a particular set of categories.

category slugs are stored in an array() as follows.

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

I want to write a foreach() {} loop so I can get the parent category, and then use that parent category and slug as variables in a link in the breadcrumbs.

This is was I have.

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; 

}

Is this the right way to get the parent-product category?

Any input or advice on this matter would be really helpful, I feel like I have searched and searched about made no progress for four hours.

Thank you for reading.

Upvotes: 0

Views: 1577

Answers (1)

vard
vard

Reputation: 4156

There is few errors in your code. First, this: $parent_name->slug will not work. $parent_name is a string, you should use $parent->slug instead. Secondly, you send an array of slug to WooCommerce is_product_category function, which expect a string, not an array. Thirdly, $cat->category_parent will not work, as $cat is a string, and not a category object. Fourth, at every iteration of your loop $parent and $parent_name are overriden.

I would suggest this code instead, that will write a breadcrumb like this with your example array (assuming Sports is the parent category of Soccer):

Home > Sports > Soccer

// 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;

Upvotes: 1

Related Questions