Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more product categories #367

Open
FreddyEE opened this issue Sep 3, 2024 · 0 comments
Open

Add more product categories #367

FreddyEE opened this issue Sep 3, 2024 · 0 comments

Comments

@FreddyEE
Copy link

FreddyEE commented Sep 3, 2024

Hi

The products on my website have like 2 -3 categories, so I need to push that data into the dataLayer. I thought in this code below, but can't get it done, how to achieve that ?

<?php

/**
 * Lists all product categories and sub-categories in a tree structure.
 *
 * @return array
 */
function list_product_categories() {
    $categories = get_terms(
        array(
            'taxonomy'   => 'product_cat',
            'orderby'    => 'name',
            'hide_empty' => false,
        )
    );

    $categories = treeify_terms($categories);

    return $categories;
}

/**
 * Converts a flat array of terms into a hierarchical tree structure.
 *
 * @param WP_Term[] $terms Terms to sort.
 * @param integer   $root_id Id of the term which is considered the root of the tree.
 *
 * @return array Returns an array of term data. Note the term data is an array, rather than
 * term object.
 */
function treeify_terms($terms, $root_id = 0) {
    $tree = array();

    foreach ($terms as $term) {
        if ($term->parent === $root_id) {
            array_push(
                $tree,
                array(
                    'name'     => $term->name,
                    'slug'     => $term->slug,
                    'id'       => $term->term_id,
                    'count'    => $term->count,
                    'children' => treeify_terms($terms, $term->term_id),
                )
            );
        }
    }

    return $tree;
}



Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant