Turn Woocommerce category ID into slug function

I am looking for a function to convert the woocommerce category id into a category slug for a breadcrumb link.

The following loop pulls the upper most product category ID for product pages. This is necessary because some of my products have 4 or 5 levels of hierarchy.

Read More

This is working fine.

$prod_terms = get_the_terms( $post->ID, 'product_cat' );

    foreach ($prod_terms as $prod_term) {

        // gets product cat id
        $product_cat_id = $prod_term->term_id;

        // gets an array of all parent category levels
        $product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' );  

        // This cuts the array and extracts the last set in the array
        $last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
        foreach($last_parent_cat as $last_parent_cat_value){
     }
    }  

At this point echo $last_parent_cat_value; would give you the ID of the highest category.

In order to turn this into a breadcrumb link I need to pull the category name. so…

        // This function turns Category Ids produced by the foreach loop above into Names
        function woocommerceCategoryName($id){
            $term = get_term( $id, 'product_cat' );
            return $term->name;        
        }

Now all I need is the slug to complete the link. so…

        //this function gets the category slug from the category id
        function get_cat_slug($cat_id) {
            $cat_id = (int) $cat_id;
            $category = &get_category($cat_id);
            return $category->slug;
        }

but when I echo

echo '<a href="' . home_url() . '/product-category/' . get_cat_slug($last_parent_cat_value) . '/">' . woocommerceCategoryName($last_parent_cat_value) . '</a>';

My Name function is working but my slug function is not.

Can anyone shine any light into my error?

when I inspect element on the front end here is my generated html…

<a href="http://home.com/product-category//">Sports</a>

Could I try and use the Name to generate the slug?

Thanks for reading.

Related posts

1 comment

  1. okay, I am not sure why the above wasn’t working, or why the following worked.

    //I copied the function to generate the name, and generated a slug instead...
    function woocommerceCategorySlug($id){
                $term = get_term( $id, 'product_cat' );
                return $term->slug;        
            }
    
    
    echo '<a href="' . home_url() . '/product-category/' . woocommerceCategorySlug($last_parent_cat_value) . '/">' . woocommerceCategoryName($last_parent_cat_value) . '</a>';
    

    Thanks again for reading, I hope this can help someone else.

Comments are closed.