2

I have a small php code. This code get the title's of the blog items. But i have a question about this code.

How can I make it. That pick-up of last 6 titles?

<ul class="blog-list">
    <?php foreach ($siblings as $sibling) : ?>
    <li><a href="<?php echo get_permalink($sibling->ID); ?>" data-nav-position="fade"><?php echo get_the_title($sibling->ID); ?></a></li>
    <?php endforeach; ?>
</ul>

Thanks for help

Mike Vierwind
  • 1,482
  • 4
  • 23
  • 44

3 Answers3

3

Easiest option with not many changes in your.

<ul class="blog-list">
    <?php $i = 0; ?>
    <?php foreach ($siblings as $sibling) : ?>
    <li><a href="<?php echo get_permalink($sibling->ID); ?>" data-nav-position="fade"><?php echo get_the_title($sibling->ID); ?></a></li>
    <?php if(++$i>=6) break; ?>
    <?php endforeach; ?>
</ul>
Kasyx
  • 3,170
  • 21
  • 32
2

If you take some of elements of array do not use foreach (see the word each?).

Use for loop instead

for($i = 0; $i < 6; ++$i){
  $sibling = $siblings[$i];

to get first 6 or

for($i = count($siblings); $i > count($siblings) - 6; --$i){
  $sibling = $siblings[$i];

to get last six (in reverse order)

EDIT

This won't work if array keys are not integers or have some empty ranges in it. You may then use array_slice() as suggested in other answer or array_pop() six times.

Voitcus
  • 4,463
  • 4
  • 24
  • 40
2

use array_slice to get last six items and then loop through it.

vishal
  • 3,993
  • 14
  • 59
  • 102