• Resolved guischarf

    (@guischarf)


    Hi,

    I am working on a template that uses different navigation bars for different categories. When displaying category pages (archive.php) I have no problems finding out which category navbar to display. This is the code I use in header.php:

    if (is_category()):
       $catID = get_cat_id(single_cat_title('', FALSE));
       $actualcat = get_category($catID);
       if ($actualcat->parent != 0):
          $catID = $actualcat->parent;
       endif;
    ...

    However, if I am in single.php I cannot find a way to get the categories of the post. This is the complete code I intend to use:

    if (is_home()):
       wp_list_categories('title_li=&depth=1');
    else:
       if (is_category()):
          $catID = get_cat_id(single_cat_title('', FALSE));
          $actual_cat = get_category($catID);
          if ($actual_cat->parent != 0):
             $catID = $actual_cat->parent;
          endif;
       elseif (is_single());
          HOW DO I GET THE CATEGORIES
       endif;
       wp_list_categories('title_li=&depth=1&child_of='.$catID);
    endif;

    Any ideas?

Viewing 2 replies - 1 through 2 (of 2 total)
  • I used this for something once that should give you what you want:

    <?php
    if (is_single( )) {
      $ID = $wp_query->posts[0]->ID;
      $postcat = get_the_category($ID);
      $cat = $postcat[0]->cat_ID;
      $parent = get_category ($cat);
        if ($parent->parent) {
          wp_list_categories ('child_of=' . $parent->parent);
          } else {
          wp_list_categories ('child_of=' . $cat);
        }
      }
    ?>
    Thread Starter guischarf

    (@guischarf)

    Thanks Michael. I will try that out. I ended up doing the following, but your solution seems way more elegant.

    ...
    elseif (is_single()):
       if (have_posts()) :
          while (have_posts()) :
             the_post();
             foreach (get_the_category() as $thecat):
                if ($thecat->parent != 0):
                   $catIDarray[] = $thecat->parent;
                else:
                   $catIDarray[] = $thecat->cat_ID;
                endif;
             endforeach;
             //if more than one category, write an algo to selec one according to a priority table.
             $catID = $catIDarray[0];
          endwhile;
       endif;
     endif;
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to get a post categories outside the loop ?’ is closed to new replies.