List all anchor links on a page

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