WordPress Alphabetical Glossary close div in loop

If you search the site, most of the “display nth post different” questions are very closely related to this one, and honestly this is more a PHP + logic question that a WordPress one.

if (have_posts()) { 
  $curr_letter=""; 
  echo '<div class="alphawrapper">';
    while (have_posts()) {
      the_post();
      $title = get_the_title();
      $title_array = explode(' ', $title);
      $second_word = $title_array[1];
      $this_letter = substr($second_word, 0, 1);
      if ($this_letter != $curr_letter) {
        if (!empty($curr_letter)) {
          echo '</div><div class="alphawrapper">';
        }
        $curr_letter = $this_letter; ?> 
        <div id="sort-<?php echo strtolower($this_letter); ?>" class="alpha_title">
          <?php echo $this_letter; ?>
        </div><!--End alpha_title--><?php 
      } ?>
      <a href="https://wordpress.stackexchange.com/questions/110875/<?php the_permalink(); ?>"><?php echo $second_word; ?></a><?php
    }
  echo '</div>';
} 

However, do not use query_posts. There are a thousand “tutorials” online recommending it, including parts of the Codex, but don’t use it.

It should be noted that using this to replace the main query on a page
can increase page loading times, in worst case scenarios more than
doubling the amount of work needed or more
. While easy to use, the
function is also prone to confusion and problems later on. See the
note further below on caveats for details.

http://codex.wordpress.org/Function_Reference/query_posts (emphasis mine)

Use a filter on pre_get_posts instead. In your theme’s functions.php put:

function pregp_wpse_110875($qry) {
  if ($qry->is_main_query() && $qry->is_archive()) {
    $qry->set('posts_per_page',20);
    $qry->set('orderby','title');
    $qry->set('order','ASC');
  }
}
add_action('pre_get_posts','pregp_wpse_110875');

Leave a Comment