Reputation: 131
Inspired from get woocommerce categories with subcategory, I am creating a drop down section and I was wondering if there is any way to remove the permalink from the parent category if it has a child category.
Here is my code example:
<?php
$args = array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
'parent' => 0
);
$product_cat = get_terms( $args );
$thumbnail_id = get_woocommerce_term_meta( $term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
foreach ($product_cat as $term){
$term_link = get_term_link( $term, 'product_cat' );
$thumb_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
$img_src = wp_get_attachment_url( $thumb_id );
//if parent category has children remove link
echo '<ul>
<li><img src="' . $img_src . '"/><a href="'.get_term_link($term->term_id).'">'.$term->name.'</a>
<ul>';
// else keep the parent link
$child_args = array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
'parent' => $term->term_id
);
$child_product_cats = get_terms( $child_args );
foreach ($child_product_cats as $child_product_cat){
echo '<li><a href="'.get_term_link($child_product_cat->term_id).'">'.$child_product_cat->name.'</a></li>';
}
echo '</ul>
</li>
</ul>';
}
How can I display a link on top level product categories terms only when there are no children terms?
Upvotes: 1
Views: 523
Reputation: 253814
The following will display a list of product category terms where the top level term will not be linked if they have any child term:
<?php
$taxonomy = 'product_cat';
$parent_terms = get_terms( array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'parent' => 0
) );
echo '<ul>';
// Loop through top level terms
foreach ( $parent_terms as $parent_term ) {
$term_link = get_term_link( $parent_term, 'product_cat' );
$thumb_id = get_woocommerce_term_meta( $parent_term->term_id, 'thumbnail_id', true );
$image_html = $thumb_id > 0 ? '<img src="' . wp_get_attachment_url( $thumb_id ) . '"/>' : '';
// Get children terms
$child_terms = get_terms( array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'parent' => $parent_term->term_id
) );
// 1. There are children terms
if( ! empty($child_terms) ) {
echo '<li>' . $image_html . $parent_term->name . '</li>
<ul>';
// Loop through children terms
foreach ( $child_terms as $term ) {
$term_link = get_term_link( $term->term_id, $taxonomy );
echo '<li><a href="' . $term_link . '">' . $term->name . '</a></li>';
}
echo '</ul>';
}
// 2. There are NOT children terms
else {
$parent_term_link = get_term_link( $parent_term->term_id, $taxonomy );
echo '<li>' . $image_html . '<a href="' . $parent_term_link . '">' . $parent_term->name . '</a></li>';
}
}
echo '</ul>';
Tested and works.
Upvotes: 2