0

I have Two parent category on my website, and each of those category have children category, like this :

constructions corollaires
    01
    02
    03
    04

Between two suns
    I
    II
    III
    IV

I'm trying to display the parent category on a archive page, and also the children category.

here is my code for the parent category :

<?php 

    $category = get_the_category(); 
    echo $category[0]->name;

?>

and for the children category :

<?php 

    $category = get_the_category(); 
    echo $category[1]->name;

?> 

what I don't understand, is that for posts who are in inside "Between two suns" category, first code echoes "Between two suns" which is the correct value, but posts who are inside "constructions corollaires", it echoes "I", the sub category instead of "constructions corollaires".

and it's the same problem with my second code, for posts who are in inside "Between two suns" category, second code echo "I" which is the correct value (1st children category), but posts who are inside "constructions corollaires", it echoes "constructions corollaires", the parent category instead of "01" for example (the children category.

I don't understand what I'm doing wrong...

all my categories are sorted in the back end.

can anybody help me with this ? It looks like an ordering issue but I really don't know how to fix this !

-1

Try to use orderby name and order asc and desc to achieve category order

      $categories = get_categories( array(
          'orderby' => 'name',
          'order'   => 'ASC'
      ) );

      foreach( $categories as $category ) {


          echo $category_names = $category[1]->name;

      } 

      //  echo wp_json_encode($category_names);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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