Paginazione in Wordpress con get_posts

Mattepuffo's logo
Paginazione in Wordpress con get_posts

Paginazione in Wordpress con get_posts

La funzione get_posts di Wordpress ci permette di iterare sui post, indicando diversi tipi di filtri / opzioni.

Di default, ovviamente, non tiene in considerazione il discorso della paginazione.

Oggi vediamo un esempio che ho appena applicato ad un sito che sto sviluppando con Wordpress ed un template custom

Ecco il codice PHP / HTML:

<?php
$postsPerPage = 10;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
	'posts_per_page' => $postsPerPage,
	'post_type' => 'post',
	'post_status' => 'publish',
	'exclude' => $excludePosts,
	'suppress_filters' => true,
	'paged' => $paged
);
$posts = get_posts($args);
if ($posts):
	foreach ($posts as $p):
		$img = get_the_post_thumbnail_url($p->ID);
		?>
		<h2>
			<a href="<?php echo get_permalink($p->ID); ?>"><?php echo $p->post_title; ?></a>
		</h2>
	<?php
	endforeach;
endif;
?>
<!-- PAGINAZIONE -->
<?php
$big = 999999999;

$count = count($args);
$offset = $postsPerPage;

$max = $count / $offset;
if (is_float($max)) {
	$max = (int)$max + 1;
}

$pagerLinks = paginate_links(array(
	'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
	'format' => '?paged=%#%',
	'current' => max(1, get_query_var('paged')),
	'total' => $max
));
if ($pagerLinks != ''):
	?>
	<div class="pager">
		<?php echo $pagerLinks; ?>
	</div>
<?php endif ?>

Qui visualizzo solo il titolo, così vi ho fatto pulizia di tutto il codice HTML inutile.

Enjoy!


Condividi

1 Commenti

  • If you can easily find any case he doesn t even oc

    If you can easily find any case he doesn t even occurred to San Sanych s burning

    08/11/2024

Commentami!