Forums

[resolved] Loop anchor links (4 posts)

  1. peterjharrison
    Member
    Posted 2 years ago #

    Hi All,

    Not sure if anyone can help me but I'm try to add anchor links with the wordpress loop but can't find anyone who has achieved what I need to do.

    I have my loop that lists about 30 posts in alphabetical order using query_posts. What I want to do is everytime time a new letter begins it adds an anchor link for the start of that letter e.g.


    [Post a1 Content]
    [Post a2 Content]


    [Post b1 Content]
    [Post b2 Content]

    etc...

    Is this at all possible and if so can you give me some advice.

    Regards
    Peter

  2. esmi
    Theme Diva & Forum Moderator
    Posted 2 years ago #

    Can you drop a copy of the code that you're currently using in that template file into the WordPress pastebin?

  3. Mike Little
    Member
    Posted 2 years ago #

    Try something like this at the top of your loop:

    <?php if (have_posts()) : ?>
        <?php $last_letter = ''; ?>
    		<?php while (have_posts()) : the_post(); ?>
                <?php $this_letter = substr(get_the_title(), 0,1);
                      if ($this_letter != $last_letter) {
                          echo '<p id="letter-' . $this_letter. '">Anchor for letter ' . $this_letter . '</p>';
                          $last_letter = $this_letter;
                      } ?>
    ... rest of loop

    note: only briefly tested but seems to work.

    By the way adding (empty) anchor tags is old school, better to add an id to an appropriate element like my example.

    Mike

  4. peterjharrison
    Member
    Posted 2 years ago #

    Hi Mike,

    Thanks for your reply! Not tried it yet but will give it a go when I get in later, the logic is really good so I don't see why it wouldn't work.

    Your advice is much appraciated as always!

    Regards
    Pete

Topic Closed

This topic has been closed to new replies.

About this Topic