michaelmcgurk
michaelmcgurk

Reputation: 6509

Split foreach results into 2 unordered lists with PHP

I have the following PHP code that pulls posts from a specific category and displays them in an unordered list.

I'd like to change this so it displays 5 <li>'s in one <ul> then creates a new <ul> for another 5 and so on.

Here is my existing code:

<?php
$args = array( 'posts_per_page' => 15, 'offset'=> 1, 'category' => $cat_ID );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); 
?>
    <li>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
<?php 
endforeach; 
wp_reset_postdata();
?>

Upvotes: 1

Views: 275

Answers (2)

Federkun
Federkun

Reputation: 36954

Another way to do it is by using array_chunk, example:

$myposts = [1,2,3,4,5,11,22,33,44,55,111,222,333,444];

foreach (array_chunk($myposts, 5) as $posts) {
    echo "<ul>\n";
    foreach ($posts as $post) {
        echo '<li>' . $post. '</li>'. "\n";
    }
    echo "</ul>\n\n";
}

Outputs:

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>

<ul>
<li>11</li>
<li>22</li>
<li>33</li>
<li>44</li>
<li>55</li>
</ul>

<ul>
<li>111</li>
<li>222</li>
<li>333</li>
<li>444</li>
</ul>

Upvotes: 1

chris85
chris85

Reputation: 23892

Here's a rough example using the modulus operator on every 5th iteration.

$myposts = array(1,2,3,4,5,6,7,8,9,10,11);
$output = '<ul>' . "\n";
foreach ($myposts as $count => $post ) {
    if ($count > 1 && $count % 5 == 0 ) {
        $output .= '</ul><ul>' . "\n";
    }
    $output .= '<li>' . $post . '</li>' . "\n" ;
}
rtrim($output, '</ul><ul>' . "\n"); //if it was the tenth iteration we don't want to open another ul
echo $output . '</ul>' . "\n";

Output:

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul><ul>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul><ul>
<li>11</li>
</ul>

Upvotes: 0

Related Questions