dominikbulaj
3/23/2016 - 12:25 PM

Closure that runs recursively to get all parent category IDs (incl. given category ID) or parent page IDs (incl. provided page object's ID)

Closure that runs recursively to get all parent category IDs (incl. given category ID) or parent page IDs (incl. provided page object's ID)

/**
 * @param WP_Post $page
 * @return array
 */
$getParentPageIds = function($page) use (&$getParentPageIds) {
    $parents = [$page->ID];

    if ($page->post_parent > 0) {
        $parentPage = get_post($page->post_parent);
        $parents = array_merge($parents, $getParentPageIds($parentPage));
    }

    return $parents;
};

// usage
$page = get_post(99);
$getParentPageIds($page); // returns array with example values: 99, 32, 1 
/**
 * @param int $id
 * @return array
 */
$getParentCategoryId = function($id) use (&$getParentCategoryId) {
    $catIds = [$id];

    $category = get_category($id);
    if ($category->category_parent > 0) {
        $catIds = array_merge($catIds, $getParentCategoryId($category->category_parent));
    }

    return $catIds;
};

// usage
$getParentCategoryId(99); // returns array with example values: 99, 91, 62, 4