WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Sub-menu based on categories please (5 posts)

  1. petethebloke
    Member
    Posted 4 years ago #

    I received an answer about sub-menus based on Pages. Now I am trying to figure it out for Categories.

    This doesn't work (it's in sidebar.php)....

    <ul>
      <?php wp_list_categories('show_count=0&title_li=&depth=1'); ?>
    </ul>
    <?php //above here is fine ?>
    <div id="subnav">
    <ul>
    <?php
      $this_categ=0;
      foreach((get_the_category()) as $category) {
      /*this is the bit that's wrong - get_the_category() gets
        all the categories because it's not in the loop - I need
        something to get one category based on where we are at
        the moment*/
        $this_categ=$category->cat_ID;
      }
      if($this_categ){
        $output = wp_list_categories ('echo=0&child_of=' . $this_categ. '&title_li=');
      }
      echo $output;
    ?>
    </ul>
  2. RGlover
    Member
    Posted 4 years ago #

    You'll probably want to do something like this:

    <ul>
      <?php wp_list_categories('show_count=0&title_li=&depth=1'); ?>
    </ul>
    <?php //above here is fine ?>
    <div id="subnav">
    <ul>
    <?php
      global $post;
      $this_categ=0;
      foreach((get_the_category($post->ID)) as $category) {
        $this_categ=$category->cat_ID;
      }
      if($this_categ){
        $output = wp_list_categories ('echo=0&child_of=' . $this_categ. '&title_li=');
      }
      echo $output;
    ?>
    </ul>

    That's untested, but passing the post ID as a parameter allows get_the_category() to work outside the post.

  3. petethebloke
    Member
    Posted 4 years ago #

    Thanks. That should be good provided the posts belong to one category, I should be able to work with that.

  4. Mark / t31os
    Moderator
    Posted 4 years ago #

    Here's a refined version that checks if you're in the loop...

    <ul>
    	<?php wp_list_categories('show_count=0&title_li=&depth=1'); ?>
    </ul>
    <div id="subnav">
    	<ul>
    	<?php if(!in_the_loop()) global $post; ?>
    	<?php $catNow = get_cat_ID(single_cat_title($post->ID,'',false)); $output = ''; ?>
    	<?php if($catNow && $catNow !== 0) $output .= wp_list_categories ('echo=0&child_of='.$catNow.'&title_li='); ?>
    	<?php echo $output; ?>
    	</ul>
    </div>

    Although i'm not sure i fully understand your usage...

  5. petethebloke
    Member
    Posted 4 years ago #

    Thanks for that. I'm trying to get a horizontal nav and subnav based on categories and subcats. I've got sidebar.php displaying horizontally. It's pretty well all working. There may be some odd results when posts are in multiple categories - that's yet to be seen.

    Thanks again,

    Pete

Topic Closed

This topic has been closed to new replies.

About this Topic