0

I am creating a theme, and I would like to show each category and its description in front page. I used the following code, but it is only showing one of the categories without a link to its page but a link for home page and also not showing the description.

<h1 class="categoryTitle">
    <a href="<?php echo esc_url( $category_link ); ?>">
        <?php foreach( (get_the_category()) as $chaine ) { 
            if($chaine->parent == 0){ 
                echo $chaine->cat_name . ' '; 
            }
        } ?>
    </a>
</h1>
<p class="cateSubTitle">
    <?php echo category_description( $category_id ); ?>
</p>

How shall I fix this?

2
  • 1
    Please format your code nicely, otherwise it's hard to read and I can assure you it's likelier someone helps you, if it's nicely formatted, so you gain something from it, aside from that it's way easier to work with for you too. May 17, 2014 at 15:43
  • There is wp_list_categories which is highly customizable, just search the site for it. May 17, 2014 at 15:47

1 Answer 1

0

Just need to use get_categories and a foreach

$cats = get_categories();
  if ( !empty( $cats ) && !is_wp_error( $cats ) ){
   foreach ( $cats as $cat ) {
    echo '<h1 class="categoryTitle"><a href="'.get_category_link( $cat->term_id ).'">'.$cat->name.'</a></h1>';
    echo '<p class="cateSubTitle">'.$cat->description.'</p>';
   }
  }

To Add each one in it's own div, just add a tag after the foreach e.g.

$cats = get_categories();
      if ( !empty( $cats ) && !is_wp_error( $cats ) ){
       foreach ( $cats as $cat ) {
        echo '<div class="divname" id="'.$cat->slug.'">';
        echo '<h1 class="categoryTitle"><a href="'.get_category_link( $cat->term_id ).'">'.$cat->name.'</a></h1>';
        echo '<p class="cateSubTitle">'.$cat->description.'</p>';
        echo '</div>';
       }
      }

There is a class so you can target all the divs at once, and each one has an id so you can target them individually, the id is the category slug e.g. toms-category

2
  • It worked, Thanks! but how to make it to show each category in its div? When I repeat that, it show the same category name.
    – Kareem
    May 17, 2014 at 15:19
  • added code to add a div around each category May 17, 2014 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.