Как изменить вывод последнего элемента wp?

Рейтинг: -3Ответов: 1Опубликовано: 08.08.2023

Не могу разобраться. Есть вывод отдельных типов записей

                            <?  $posts = get_posts("post_type=jobs&orderby=date&numberposts=5");
if ($posts) : ?>
               <?  foreach ($posts as $post) : setup_postdata($post); ?>
               <a href="<?php echo get_permalink(); ?>"><? the_title();?> ,</a>
               <?
endforeach;
           endif; ?>

Как сделать так чтобы последний элемент был без запятой и вместо него текст

   <a href="<?php echo get_permalink(); ?>"><? the_title();?> и другие</a>

Ответы

▲ 1Принят

Если текущий ключ элемента равен последнему ключу массива, вместо запятой пишем " и другие"

<?$posts = get_posts("post_type=jobs&orderby=date&numberposts=5");
if ($posts):
  $comma = ', ';
  $lKey = array_key_last($posts);
  foreach ($posts as $key => $post):
    setup_postdata($post);
    if ($key == $lKey) $comma = ' и другие';?>
    <a href="<? echo get_permalink(); ?>"><? the_title();?></a><? echo $comma;?><?
  endforeach;
endif;?>