WordPress.org

Ready to get started?Download WordPress

Forums

Hierarchical list of menuitems (1 post)

  1. stijnhoste
    Member
    Posted 1 year ago #

    I'm trying to make a list of menuitems based on the page I'm viewing. For example if I'm on the page History, I have a menu with all the subcategories under history and the posts in these subcategories. Also the menuitems have to be clickable.

    So basically I want this:

    MAIN CAT = pagename

    SUB CAT1
    - post1
    - post2

    SUB CAT2
    - post1
    - post2

    This is what I hacked together so far:

    <div id="menu">
    <ul>
        <?php
        $page_title = wp_title();
        preg_replace( "/[^a-z0-9 ]/i", "", $page_title);
        strtolower($page_title);
    
        $cat_id = get_cat_ID($page_title);
        //get terms (e.g. categories or post tags), then display all posts in each retrieved term
        $taxonomy = 'category';//  e.g. post_tag, category
        $param_type = 'category__in'; //  e.g. tag__in, category__in
        $term_args=array(
          'orderby' => 'name',
          'order' => 'ASC',
          'child_of' => '$cat_id'
        );
        $terms = get_terms($taxonomy,$term_args);
        if ($terms) {
          foreach( $terms as $term ) {
            $args=array(
              "$param_type" => array($term->term_id),
              'post_type' => 'post',
              'post_status' => 'publish',
              'showposts' => -1,
              'ignore_sticky_posts'=> 1
              );
            $my_query = null;
            $my_query = new WP_Query($args);
            if( $my_query->have_posts() ) {
    
              echo '<li><a href="' . get_category_link( $term->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name. '</a> ';
    
              while ($my_query->have_posts()) : $my_query->the_post(); ?>
                <ul><li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li></ul>
               <?php
                     endwhile;
            }
          }
        }
        wp_reset_query();  // Restore global post data stomped by the_post().
        ?>
    </ul>
    </div>

    And now it just prints the title of the page.

Topic Closed

This topic has been closed to new replies.

About this Topic