0

I was trying to make a navigation menu of all the anchor links on a page (similar to wikipedia) but couldn't find out how. I tried to find a plugin that could do it, but they only listed the anchors of a single post.

I made a custom page with the following code:

get_header(); ?>

<main id="content" class="site-content" role="main">

    <?php query_posts('category_name=Artemis-Header'); ?>

    <?php while ( have_posts() ) : the_post(); ?>

        <?php the_content(); ?>

    <?php endwhile; // end of the loop. ?>

    <?php query_posts('category_name=Artemis'); ?>

    <?php while ( have_posts() ) : the_post(); ?>

        <?php get_template_part( 'content', 'page' ); ?>

        <?php comments_template( '', true ); ?>

    <?php endwhile; // end of the loop. ?>

</main><!-- #content .site-content -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

and it displays a header, followed by all the posts that are part of the category "Artemis". When on this page, I'd like there to be a list of anchor links to all of the posts (later I'll move those links to a fixed sidebar, to make navigation easy).

Any help would be appreciated

2

1 Answer 1

1

In short, you'll run the loop twice. The first time creating the links. The second time creating the posts. The trick is to figure out what the ID will be for the post. It needs to be something unique: We could use the slug or the post ID.

    <?php
    // I'm going to get the posts only once, but then loop through them twice
    $query = new WP_Query( 'category_name=Artemis' );
    ?>

    <?php // Create the links ?>
    <ol>
      <?php while( $query->have_posts() ): $query->the_post(); ?>
        <li><a href="#post-<?php the_ID(); ?>"><?php the_title(); ?></a></li>
      <?php endwhile; ?>
    </ol>

    <?php // Now show the posts ?>
    <?php
      $query->rewind_posts(); // Reset the pointer to the start
      while( $query->have_posts() ): $query->the_post(); ?>
    <div id="#post-<?php the_ID(); ?>">
      <?php // code to display the content of the post here
    </div>
    <?php endwhile; ?>
  1. We created a reusable WP_Query object
  2. The id we add to the posts and we link to is the pattern post-[post_ID] 3 We loop through the query twice, once for the link, the second for the content
  3. Remember to call rewind_posts() to reset the internal counter
1
  • This worked perfectly. You are a wonderfully helpful person, and your code is well documented - Thank you.
    – asemahle
    Feb 14, 2014 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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