0

I am looking for help in how to paginate my foreach output. I've looked at other questions and answers and cannot find a solution that works for me or that I can figure out on my own. Right now my code, which is below, outputs everything into table rows. My problem, of course, is that it dumps all data on a single page -- hence the reason I want pagination. I want to paginate for every 11 items on the page. The page is a magazine archive, and there are 11 issues pear year -- so every page is equal to 1 year of our magazine. The first page should host issues 1-11 and page two should host issues 12 through 22, etc. We have 10 years worth of magazine issues. Any help would be greatly appreciated. Thank you!

<table>
<tr>
<?php $col = 0; ?>
<?php foreach (get_terms('term') as $cat) : ?>

<?php if ($col > 0 && $col % 3 == 0): ?>
</tr>
<tr>
<?php endif; ?>
<?php $col++; ?>

<td>

<a href="<?php echo get_term_link($cat->slug, 'term'); ?>"><strong><?php echo $cat->name; ?></strong></a><br>

<em><a href="<?php echo get_term_link($cat->slug, 'term'); ?>"><?php echo $cat->description; ?></a></em><br>

<a href="<?php echo get_term_link($cat->slug, 'term'); ?>"><img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" /></a>
</td>
<?php endforeach; ?>
</tr>
</table>

1 Answer 1

-1

Here is the code I used to solve my problem:

<?php
$url = $_SERVER["REQUEST_URI"];
$segments = explode('/', $url);
$page = is_numeric($segments[count($segments)-2]) ? $segments[count($segments)-2] : 1;
$next = $page + 1;
$prev = $page - 1;
$issues_per_page = 11;
$lastpage = ceil(wp_count_terms( 'mag') / $issues_per_page) ;
?>

<?php wp_count_terms( 'mag' ); ?>

<table>
<tr>
<?php $col = 0; ?>
<?php foreach (get_terms('mag', array('offset' => ($page - 1) * $issues_per_page, 'number' => $issues_per_page)) as $cat) : ?>

<?php if ($col > 0 && $col % 3 == 0): ?>
</tr>
<tr>
<?php endif; ?>
<?php $col++; ?>

<td>

<a href="<?php echo get_term_link($cat->slug, 'mag'); ?>"><strong><?php echo $cat->name; ?></strong></a><br>

<em><a href="<?php echo get_term_link($cat->slug, 'mag'); ?>"><?php echo $cat->description; ?></a></em><br>

<a href="<?php echo get_term_link($cat->slug, 'mag'); ?>"><img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" /></a>
</td>
<?php endforeach; ?>
</tr>
</table>


<?php if ($prev > 0) : ?>
<a href="/mag-archive?page=<?php echo $prev; ?>">Previous</a>
<?php endif ?> 
<?php if ($page < $lastpage) : ?>
<a href="/mag-archive?page=<?php echo $next; ?>">Next</a>
<?php endif ?>
1
  • Why did someone vote this down and provide no explanation as to why it is a poor solution? Commented Apr 17, 2017 at 20:45

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.