WordPress.org

Ready to get started?Download WordPress

Forums

Show only child categories for single.php (5 posts)

  1. thealchemyst
    Member
    Posted 5 years ago #

    I have a 2 level navigation. On the top I'm listing only the parent categories and what I want to accomplish is when I click on a particular post I want to have a sidebar where it lists the child categories for the particular parent category.

    For more clear presentation, here is a sample menu

    Technology
    - Gadgets
    - Microsoft
    - Hardware
    Science
    Entertainment

    Now, suppose I have a post under Technology. When clicked single.php is shown and I want to show a sidebar with the child categories (Gadgets, Microsoft, Hardware) from the active parent category.

    A bonus would be if this can be accomplishable even if I have a post filed under a child category (Gadgets for example) and still list the sibling categories.

  2. MichaelH
    Member
    Posted 5 years ago #

    This in your sidebar:

    <?php
    if (is_category( )) {
      $cat = get_query_var('cat');
      $parent = get_category ($cat);
      if ($parent->parent) {
        wp_list_categories ('child_of=' . $parent->parent);
        } else {
        wp_list_categories ('child_of=' . $cat);
      }
    }
    ?>
  3. MichaelH
    Member
    Posted 5 years ago #

    Oops, you wanted this for single.php, not category like above!

    <?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);
        }
      }
    ?>
  4. bkbdesign
    Member
    Posted 4 years ago #

    This is exactly what I've been looking for... Anyway to stop it from displaying the word "categories" in front of the resulting list??

  5. bkbdesign
    Member
    Posted 4 years ago #

    Nevermind, I figured it out. If anyone else has same question:

    <?php
    if (is_category( )) {
      $cat = get_query_var('cat');
      $parent = get_category ($cat);
      if ($parent->parent) {
        wp_list_categories ('title_li=&child_of=' . $parent->parent);
        } else {
        wp_list_categories ('title_li=&child_of=' . $cat);
      }
    }
    
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.