Implementing Custom Post Type Pagination without get_query_var('paged')
Pagination is a crucial feature when dealing with large amounts of content in WordPress. It allows users to navigate through different pages of content, improving usability and performance. While the get_query_var('paged')
function is commonly used for pagination, it may conflict with special page pagination in some cases. In this tutorial, we will explore an alternative approach to achieve pagination for a custom post type without relying on get_query_var('paged')
.
Step 1: Set up the Custom Post Type
First, ensure that you have a custom post type set up in your WordPress installation. If you haven’t created one yet, you can follow these steps:
- Open your theme’s
functions.php
file or create a custom plugin. - Add the following code to register your custom post type:
function custom_post_type_registration() {
$args = array(
'public' => true, // Set to false if you want to hide it from the front-end
'label' => 'Your Custom Post Type', // Replace with the desired label
// Add additional arguments as per your requirements
);
register_post_type( 'your_custom_post_type', $args );
}
add_action( 'init', 'custom_post_type_registration' );
Remember to replace 'Your Custom Post Type'
with the desired label for your custom post type.
Step 2: Prepare the Pagination Code
Next, let’s prepare the code for implementing custom post type pagination without get_query_var('paged')
. This code will be placed within a PHP file in your WordPress theme or a custom plugin.
<?php
$posts_per_page = 10; // Number of posts per page
$current_page = isset( $_GET['page'] ) ? absint( $_GET['page'] ) : 1; // Current page number
$offset = ( $current_page - 1 ) * $posts_per_page; // Offset for the query
$args = array(
'post_type' => 'your_custom_post_type',
'posts_per_page' => $posts_per_page,
'offset' => $offset,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Display your custom post content here
the_title('<h2>', '</h2>');
the_content();
}
// Pagination links
$total_pages = ceil( $query->found_posts / $posts_per_page ); // Calculate the total number of pages
if ( $total_pages > 1 ) {
echo '<div class="pagination">';
for ( $i = 1; $i <= $total_pages; $i++ ) {
$active_class = ( $i === $current_page ) ? 'active' : ''; // Add CSS class for the active page
echo '<a class="' . $active_class . '" href="?page=' . $i . '">' . $i . '</a>';
}
echo '</div>';
}
}
// Restore original post data
wp_reset_postdata();
?>
Step 3: Customize the Code for Your Needs
In the above code snippet, make sure to replace 'your_custom_post_type'
with the slug or name of your custom post type. Adjust the $posts_per_page
variable to determine how many posts you want to display per page.