businessdad icon

WooCommerce - Get product categories and their parents

businessdad | PRO | 05/10/16 04:41:19 PM UTC | 0 ⭐ | 2096 👁️ | Never ⏰ | []
PHP |

2.04 KB

|

None

|

0 👍

/

0 👎

/**
 * Returns the categories that are parent to a specific category.
 *
 * Need help customising the code for your need? Hire us on Codeable: http://bit.ly/codeable_aelia
 *
 * @param int category_id The ID of the category for which to retrieve the
 * parent categories
 * @return array An array of categories.
 * @author Aelia <[email protected]>
 */
function aelia_get_parent_categories($category_id) {
  $parent_categories = array();
  $parent_categories_ids = get_ancestors($category_id, 'product_cat');
 
  foreach($parent_categories_ids as $category_id) {
    $category = get_term_by('id', $category_id, 'product_cat');
    $parent_categories[$category->slug] = $category->name;
  }
  return $parent_categories;
}
 
/**
 * Returns the categories to which a product belongs.
 *
 * @param WC_Product product A WooCommerce product.
 * @param bool return_raw_categories Indicates if the raw category data should
 * be return. When set to false, a simpler array with category slugs and names
 * is returned.
 * @return array An array of categories, with slugs as keys and category names 
 * as values.
 * @author Aelia <[email protected]>
 */
function aelia_get_product_categories($product, $return_raw_categories = false) {
  $result = array();
  $categories = wp_get_post_terms($product->id, 'product_cat');
 
  if(is_array($categories) && !$return_raw_categories) {
    $parent_categories = array();
    // Retrieve the parent categories of each category to which
    // the product is assigned directly
    foreach($categories as $category) {
      // Using array_merge(), we keep a list of parent categories
      // that doesn't include duplicates
      $parent_categories = array_merge($parent_categories, aelia_get_parent_categories($category->term_id));
    }
    // When we have the full list of parent categories, we can merge it with
    // the list of the product's direct categories, producing a single list
    $categories = array_merge($parent_categories, wp_list_pluck($categories, 'name', 'slug'));
  }
  return $categories;
}

Comments