Paginazione WordPress con custom post type?
Ho cercato ovunque sul web per trovare una soluzione, ma nessuna sembra funzionare nel mio caso. Qualcuno può aiutarmi e spiegarmi cosa c'è che non va? Ho passato 3 ore a debugghare senza trovare il problema.
Ecco il mio codice:
global $paged;
global $wp_query;
wp_reset_query();
$per_page = get_option('posts_per_page');
$cat_cars = get_term_by('slug', 'cars', 'category');
$page_links_total = ceil($cat_cars->count / $per_page);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'cars',
'post_status' => 'publish',
'cat' => $cat_cars->term_id,
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => $per_page,
'paged' => $paged
);
$page_links = paginate_links(array(
'base' => add_query_arg('paged', '%#%'),
'format' => '',
'prev_text' => __('«'),
'next_text' => __('»'),
'end_size' => 2,
'mid_size' => 1,
'type' => 'plain',
'total' => $page_links_total,
'current' => $paged
));
$car_query = new WP_Query($args);
E poi chiamo have_posts
, the_post
, etc..
Questa parte funziona, fino a quando non vado alla seconda pagina della mia paginazione e non trovo più nulla.

Ho avuto un problema simile di recente e ho determinato che la causa fosse che quando WordPress esegue una query per i post in una categoria, cerca prima i post con post_type uguale a 'post' prima di arrivare al punto in cui esegui la query per post_type 'any' o un qualche custom post type. Questo non causa problemi nella prima pagina perché, anche se non ci sono post, chiama il tuo template. Tuttavia, dalla pagina 2 in poi, non trova alcun post con post_type 'post', quindi carica il template 404 prima ancora che il tuo template abbia la possibilità di modificare il parametro post_type.
È un bug? Questa è una buona domanda. Direi di sì perché ci si aspetterebbe che, se registri la tassonomia 'category' su altri post_type, tutti i post_type dovrebbero apparire in quell'archivio, non solo i post standard.
Spero che questo ti sia utile.

Ho questo codice (ripulito) su un sito, che richiama i post da un custom post type, e in fondo la paginazione, se ci sono più di 10 post:
<?php $wp_query = new WP_Query(); $wp_query->query('post_type=mycpt&showposts=10'.'&paged='.$paged);
while ($wp_query->have_posts()) : $wp_query->the_post();?>
<h3><?php the_title(); ?></h3>
<?php the_content();?>
<?php endwhile; wp_reset_query(); ?>
<?php if ( $wp_query->max_num_pages > 1 ) { ?>
<div id="nav-below" class="navigation">
<div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">«</span> Consigli vecchi', 'twentyten' ) ); ?></div>
<div class="nav-next"><?php previous_posts_link( __( 'Consigli più recenti <span class="meta-nav">»</span>', 'twentyten' ) ); ?></div>
</div>
<?php } ?>
Spero possa essere utile.
