Michael.A
Michael.A

Reputation: 31

Creating Category list in Wordpress

Hello I am trying to create a Categories list in my Sidebar. However, all the information I am finding regarding the category list doesn't allow me to style the list. Ideally I would like to only list the top 5 most popular but right now I just want to figure out how to properly access the data.

when I use this code

           <?php
               $terms = get_terms('category'); /*Name Of category*/
               foreach ( $terms as $term ) {
               echo $term->name.'<br/>  '.$term->count.'<br/>';
                }
                ?>

every thing works ok but I am unable to add any css or html

     <div class="category" data-aos="fade-left" data-aos-delay="300">
          <h2>Popular Categories</h2>

          <?php
           $terms = get_terms('category'); /*Name Of category*/
           foreach ( $terms as $term )
            ?>
       
          <ul class="category-list">
            <li class="list-items" data-aos="fade-left" data-aos-delay="400">
              <a href="#"><?php echo $term->name. ;?> </a> <span>(<?php echo $term->count. ;?> ) 
             </span>
            </li>
          </ul>
      <?php endforeach; wp_reset_query();?>
        </div>

any help would be great!

Upvotes: 1

Views: 105

Answers (1)

ariefbayu
ariefbayu

Reputation: 21979

You are using two different kind of foreach. The first one, you use curly brackets syntax:

foreach($variables as $each){
    //codes
}

It works fine as it is as intended format. The second one failed due to wrong syntax usage. To use foreach() .. endforeach;, you need to add colon sign (:) right after foreach declaration:

foreach():
    //codes
endforeach;

Without this one colon sign character, your code will be treated like the first version, but without curly brackets.

Therefore, your code should look like this:

<?php
$terms = get_terms('category'); /*Name Of category*/
foreach ( $terms as $term ):
?>
   
<ul class="category-list">
  <li class="list-items" data-aos="fade-left" data-aos-delay="400">
    <a href="#"><?php echo $term->name. ;?> </a> <span>(<?php echo $term->count. ;?> )</span>
  </li>
</ul>
<?php
endforeach;
wp_reset_query();
?>

Upvotes: 1

Related Questions