businessdad

WooCommerce - Get product categories and their parents

May 10th, 2016
582
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Returns the categories that are parent to a specific category.
  3.  *
  4.  * Need help customising the code for your need? Hire us on Codeable: http://bit.ly/codeable_aelia
  5.  *
  6.  * @param int category_id The ID of the category for which to retrieve the
  7.  * parent categories
  8.  * @return array An array of categories.
  9.  * @author Aelia <support@aelia.co>
  10.  */
  11. function aelia_get_parent_categories($category_id) {
  12.   $parent_categories = array();
  13.   $parent_categories_ids = get_ancestors($category_id, 'product_cat');
  14.  
  15.   foreach($parent_categories_ids as $category_id) {
  16.     $category = get_term_by('id', $category_id, 'product_cat');
  17.     $parent_categories[$category->slug] = $category->name;
  18.   }
  19.   return $parent_categories;
  20. }
  21.  
  22. /**
  23.  * Returns the categories to which a product belongs.
  24.  *
  25.  * @param WC_Product product A WooCommerce product.
  26.  * @param bool return_raw_categories Indicates if the raw category data should
  27.  * be return. When set to false, a simpler array with category slugs and names
  28.  * is returned.
  29.  * @return array An array of categories, with slugs as keys and category names
  30.  * as values.
  31.  * @author Aelia <support@aelia.co>
  32.  */
  33. function aelia_get_product_categories($product, $return_raw_categories = false) {
  34.   $result = array();
  35.   $categories = wp_get_post_terms($product->id, 'product_cat');
  36.  
  37.   if(is_array($categories) && !$return_raw_categories) {
  38.     $parent_categories = array();
  39.     // Retrieve the parent categories of each category to which
  40.     // the product is assigned directly
  41.     foreach($categories as $category) {
  42.       // Using array_merge(), we keep a list of parent categories
  43.       // that doesn't include duplicates
  44.       $parent_categories = array_merge($parent_categories, aelia_get_parent_categories($category->term_id));
  45.     }
  46.     // When we have the full list of parent categories, we can merge it with
  47.     // the list of the product's direct categories, producing a single list
  48.     $categories = array_merge($parent_categories, wp_list_pluck($categories, 'name', 'slug'));
  49.   }
  50.   return $categories;
  51. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×