blackhill24
blackhill24

Reputation: 452

woocommerce category depth as condition with if statement

Im not sure the best way to proceed here.

I have categories laid out like this (a simplified version):

-fruit
--apple
---large
---small

--banana
---var1
----large
----small
---var2
----small
----large

I want to use the depth of a category as the condition in an if statement to achieve something like this:

if category is depth 2 (apple>large) do this

else if the category is depth 3 (banana>var1>small) do something else.

Ive tried using the function from here but have been unable to get anything back other than an empty array! http://www.devdevote.com/cms/wordpress-hacks/get_depth.html

Upvotes: 4

Views: 1112

Answers (2)

DevLime
DevLime

Reputation: 1027

You could use get_ancestors() and then count() on the items returned. From there is will be simple logic.

As a function this would look like:

function so50409656_count_ancestors( $object_id, $object_type ='', $resource_type='' ) {

    $terms = get_ancestors( $object_id, $object_type, $resource_type );

    return count($terms) + 1;

}

And then called like this:

$term_depth = so50409656_count_ancestors( $term->term_id, 'your_term_type', 'taxonomy' );

if ( $term_depth === 1 ) :
    // ..your top level ancestor action
elseif ( $term_depth === 2 ) :
    // ..your direct child choice of actions here
elseif ( $term_depth === 3 ) :
    // ..your second level child action here
endif;

EDIT:

Clarified that a result of 1 will be the top level ancestor as per the OP request for something like large (in apple>large) to be equal to 2

Upvotes: 4

Jaydp
Jaydp

Reputation: 1039

You can use below recursive function

function hierarchical_product_cat($category = 0)
{
    $result = '';
    $args = array('parent' => $category);
    $next = get_terms('product_cat', $args);

    if ($next) {
        $result .= '<ul>';
        foreach ($next as $cat) {
            $result .= '<li><a href="' . get_term_link($cat->slug, $cat->taxonomy) . '" title="'.$cat->name.'" ' . '>' . $cat->name . ' (' . $cat->count . ')' . '</a>';
            $result .= $cat->term_id !== 0 ? hierarchical_product_cat($cat->term_id) : null;
        }
        $result .= '</li>';
        $result .= '</ul>';
    }
    return $result;
}
echo hierarchical_product_cat();

Upvotes: 0

Related Questions