A
A
awerka742018-08-20 22:25:07
WordPress
awerka74, 2018-08-20 22:25:07

How to spell a custom post type?

Hello. I have a dictionary in wordpress. Entries are listed alphabetically. Here is the code:

<?php 
$posts = get_posts( array ( 'post_type' => 'dictionary', 'order' => 'ASC', 'orderby' => 'title', 'caller_get_posts'=>1,  'posts_per_page' => -1 ) );


foreach( $posts as $k => $post ){

// первая буква
$fl = get_first_letter( $post->post_title );
$prev_fl = isset( $posts[ ($k-1) ] ) ? get_first_letter( $posts[ ($k-1) ]->post_title ) : '';

if( $prev_fl !== $fl ) 

// Буква
echo '<div class="dictionary-block"><div class="padding-block"><b>'.$fl.'</b><ul class="dictionary-list">'; ?>

<li><strong><?php the_title() ?></strong><p><?php the_field("desc") ?></p><a href="<?php the_field("url") ?>" class="link">Подробнее</a></li></ul></div></div>

<?php } 

wp_reset_postdata();

function get_first_letter( $str ){
  return mb_substr($str, 0, 1, 'utf-8');
} ?>

If there is one entry in a block with one letter, everything works fine, for example:
A
Apricot
B
Bagel
C
Helicopter
BUT! If more than two, the template flies:
A
Pineapple
//
Apricot template flies here
B
Helicopter The
question is: how to remake this code so that records of one letter are displayed in a group? Like this:
<div class="dictionary-block">
<div class="padding-block">
<b>А</b>
<ul class="dictionary-list">
<li>
<strong>Ананас</strong>
<p>Описание ананаса</p>
<a href="#" class="link">Подробнее</a>
</li>
<li>
<strong>Абрикос</strong>
<p>Описание абрикоса</p>
<a href="#" class="link">Подробнее</a>
</li>
</ul>
</div>
</div>

Those. within the same group by the LI list

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Pupkin, 2018-08-21
@HectorPrima

echo '<div class="dictionary-block"><div class="padding-block">';
foreach( $posts as $k => $post ){
  setup_postdata($post);
  $fl = get_first_letter( $post->post_title );
  if( $prev_fl !== $fl ){
      if (isset($prev_fl))
      	echo "</ul>";
    echo '<b>'.$fl.'</b><ul class="dictionary-list">';
  }
  echo '<li><strong>' . get_the_title() . '</strong><p>' . the_field("desc") . '</p><a href="' . the_field("url") . '" class="link">Подробнее</a></li>';
  $prev_fl = $fl;
}
if (isset($prev_fl))
  echo "</ul>";
echo '</div></div>';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question