jeudi 29 juillet 2021

Issue with foreach, if, else php

I have been trying to add else to my foreach loop where it shows categories and subcategories. But if there is no categories available then I want it to show a text where it tells that there is no categories or products in categories.

Right now it shows the text that there is no products in categories anyways even if there is some categories shown.

<?php

  $taxonomy     = 'product_cat';
  $orderby      = 'menu_order';  
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no  
  $title        = '';  
  $empty        = 1;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
 $all_categories = get_categories( $args );
 
      echo '<ul>';
      echo '<div class="category"><h1>CATEGORIES</h1></div>';
 
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id; 
        
         echo '<li class="parentcategory">';
        echo '<a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';
        echo '</li>';
        

        $args2 = array(
                'taxonomy'     => $taxonomy,
                'child_of'     => 0,
                'parent'       => $category_id,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                echo '<li class="subcategory">';
                echo  '<a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>' ;
                echo '</li>';
            }   
        } 
    }    
else {
          echo '<li>';
          echo '<p>';
          echo 'Currently there is no categories made';
          echo ' or any products in the categories';
          echo '</p>';
          echo '</li>';

   } 
}

 echo '</ul>';
 
?>

enter image description here

Aucun commentaire:

Enregistrer un commentaire