jmccole83
10/18/2019 - 9:29 AM

WordPress | Group Posts by first letter

{{--
  https://stackoverflow.com/a/57190667
--}}
@php

  $posts = get_posts(
      array(
          'post_type' => 'glossary',
          'post_status' => 'publish',
          'posts_per_page' => -1,
          'orderby' => 'title',
          'order' => 'ASC',
      )
  );
  $alphas = range('A', 'Z');
  $key_keyed_posts = array();

  if ( $posts ) {
      foreach ( $posts as $post ) {
          $first_letter = strtoupper( substr( $post->post_title, 0, 1 ) );

          if ( ! array_key_exists( $first_letter, $key_keyed_posts ) ) {

              $key_keyed_posts[ $first_letter ] = array();
          }

           $key_keyed_posts[ $first_letter ][] = $post;
      }

  }

@endphp

@foreach ($key_keyed_posts as $key => $value)
  @foreach ($value as $val)
    <div class="d-block mb-4 pr-5">
      <span>{!! $val->post_title !!}: {!! $val->post_content !!}</span>
    </div>
  @endforeach
@endforeach