WordPress custom query on a page with pagination
<?php
// Define custom query parameters
$custom_query_args = array(
'post_type' => 'servizi',
'showposts' => 3,
'post_parent' => 0,
);
// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
// Instantiate custom query
$custom_query = new WP_Query( $custom_query_args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $custom_query;
// Output custom query loop
if ( $custom_query->have_posts() ) : ?>
<div class="listing-services col-group-row no-extgut no-marg">
<?php while ( $custom_query->have_posts() ) : $custom_query->the_post();?>
<div class="col one-fourth m-1-2 s-1-1">
<article class="item-service" data-mh="grp-service">
<div class="icon"><?php echo file_get_contents( get_field('ico_serv_svg') ); ?></div>
<h3 class="item-title"><a href="<?php the_permalink();?>"><?php the_title();?></a></h3>
<div class="text"><p><?php echo excerpt(12); ?></p></div>
<a href="<?php the_permalink();?>" class="readmore"><i class="fa fa-long-arrow-right" aria-hidden="true"></i></a>
</article>
</div>
<?php endwhile; ?>
</div>
<?php endif;
// Reset postdata
wp_reset_postdata(); ?>
<?php
// Custom query loop pagination
previous_posts_link( 'Older Posts' );
next_posts_link( 'Newer Posts', $custom_query->max_num_pages );
// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
?>
add_action('init', 'custom_rewrite_basic');
function custom_rewrite_basic() {
global $wp_post_types;
foreach ($wp_post_types as $wp_post_type) {
if ($wp_post_type->_builtin) continue;
if (!$wp_post_type->has_archive && isset($wp_post_type->rewrite) && isset($wp_post_type->rewrite['with_front']) && !$wp_post_type->rewrite['with_front']) {
$slug = (isset($wp_post_type->rewrite['slug']) ? $wp_post_type->rewrite['slug'] : $wp_post_type->name);
$page = get_page_by_slug($slug);
if ($page) add_rewrite_rule('^' .$slug .'/page/([0-9]+)/?', 'index.php?page_id=' .$page->ID .'&paged=$matches[1]', 'top');
}
}
}
function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) {
global $wpdb;
$page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s AND post_status = 'publish'", $page_slug, $post_type ) );
return ($page ? get_post($page, $output) : NULL);
}
// Ricordarsi che questi parametri siano settati così!
$args = array(
'hierarchical' => true,
'has_archive' => false,
'rewrite' => array(
'slug' => 'servizi', // if you need slug
'with_front' => false
)
);