מסדר קטגוריות פרורי לחם

PHOTO EMBED

Wed Nov 27 2024 13:05:27 GMT+0000 (Coordinated Universal Time)

Saved by @odesign

add_filter('woocommerce_get_breadcrumb', 'precise_custom_woocommerce_breadcrumbs', 20, 2);
function precise_custom_woocommerce_breadcrumbs($crumbs, $breadcrumb) {
    // הסרת עמוד הבית
    if (isset($crumbs[0]) && $crumbs[0][0] == get_bloginfo('name')) {
        array_shift($crumbs);
    }

    // אם אנחנו בעמוד מוצר
    if (is_product()) {
        $product = wc_get_product();
        $product_categories = get_the_terms($product->get_id(), 'product_cat');
       
        if ($product_categories) {
            // מציאת הקטגוריה העמוקה ביותר
            $deepest_category = null;
            foreach ($product_categories as $category) {
                if (!$deepest_category || count(get_ancestors($category->term_id, 'product_cat')) >
                    count(get_ancestors($deepest_category->term_id, 'product_cat'))) {
                    $deepest_category = $category;
                }
            }

            if ($deepest_category) {
                // הכנת מערך חדש של פירורי לחם
                $new_crumbs = [];
               
                // קבלת ההורים של הקטגוריה
                $term_parents = get_ancestors($deepest_category->term_id, 'product_cat');
                $term_parents = array_reverse($term_parents);

                // הוספת ההורים
                foreach ($term_parents as $parent_id) {
                    $parent_term = get_term($parent_id, 'product_cat');
                    $new_crumbs[] = [$parent_term->name, get_term_link($parent_term)];
                }

                // הוספת הקטגוריה העמוקה ביותר
                $new_crumbs[] = [$deepest_category->name, get_term_link($deepest_category)];

                // הוספת שם המוצר
                $new_crumbs[] = [$product->get_name(), get_permalink($product)];

                // החלפת הפירורי לחם המקוריים
                $crumbs = $new_crumbs;
            }
        }
    }

    // אם אנחנו בדף קטגוריה
    if (is_product_category()) {
        $current_category = get_queried_object();
        $ancestors = get_ancestors($current_category->term_id, 'product_cat');
        $ancestors = array_reverse($ancestors);

        // הכנת מערך חדש של פירורי לחם
        $new_crumbs = [];

        // הוספת ההורים
        foreach ($ancestors as $ancestor_id) {
            $ancestor_term = get_term($ancestor_id, 'product_cat');
            $new_crumbs[] = [$ancestor_term->name, get_term_link($ancestor_term)];
        }

        // הוספת הקטגוריה הנוכחית
        $new_crumbs[] = [$current_category->name, get_term_link($current_category)];

        // החלפת הפירורי לחם המקוריים
        $crumbs = $new_crumbs;
    }

    return $crumbs;
content_copyCOPY