0

Alright, so here's what I'd like to do. I'm wanting to create a "glossary" using WordPress posts of a specific post type. In other words, the "title" and description" of each glossary entry would be pulled from meta values in each post. In the end, it should look something like this, where each "entry" is generated from a post:

A
Android: Description
Apple: Description
Aztec: Description

B
Bacon: Description

C
Cat: Description
Category: Description

The "title" and "description" of each glossary entry is pulled from meta values in the respective posts. The code I have so far:

// A function to display recent glossary posts
function list_glossary_posts() {
global $post;
$args = array( 'posts_per_page' => -1, 'post_type' => 'crb_glossary', 'orderby'=> 'meta_value', 'meta_key' => 'glossary_title', 'order' => 'ASC' );
$postslist = get_posts( $args );
ob_start();


foreach ( $postslist as $post ) :

  setup_postdata( $post );

  $glossary_title = get_post_custom_values($key = 'glossary_title');
  $glossary_description = get_post_custom_values($key = 'glossary_description');
  $glossary_letter = substr($glossary_title[0], 0, 1);

  ?>

  <h3><?php echo $glossary_letter; ?></h3>
    <p><a href="<?php the_permalink(); ?>"><?php echo $glossary_title[0]; ?></a>: <?php echo $glossary_description[0]; ?></p>
  <?php

endforeach;

wp_reset_postdata();

$output = ob_get_clean();
return $output;

}

// A shortcode for the glossary
add_shortcode('list_glossary_posts', 'list_glossary_posts');

Here's what I'm struggling with. I want each unique $glossary_letter variable to display once. For example, I don't want this:

A
Android: Description

A
Apple: Description

A
Aztec: Description

B
Bacon: Description

C
Cat: Description

C
Category: Description

Help!

1 Answer 1

1

Declare a $previous_letter variable, and at the end of the foreach give it the value of the current $glossary_letter. Before of show the $glossary_letter make an if condition. If $glossary_letter is different to the $previous_letter then show it.

$previous_letter = null;

foreach ( $postslist as $post ) :

  setup_postdata( $post );

  $glossary_title = get_post_custom_values($key = 'glossary_title');
  $glossary_description = get_post_custom_values($key = 'glossary_description');
  $glossary_letter = substr($glossary_title[0], 0, 1);

  ?>

  if ( $glossary_letter !== $previous_letter ):
      <h3><?php echo $glossary_letter; ?></h3>
  endif;

    <p><a href="<?php the_permalink(); ?>"><?php echo $glossary_title[0]; ?></a>: <?php echo $glossary_description[0]; ?></p>
  <?php

$previous_letter = $glossary_letter;
endforeach;
1
  • thanks for the solution! It's working great. Only edit I had was adding the PHP tags around the if statement. Commented Nov 25, 2017 at 16:57

Your Answer

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

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