简体   繁体   中英

Making Pagination work with home.php

I can't seem to create a proper numeric pagination links on my home.php (ie the page containing all the posts sorted by date). Been scouring the WP developer handbook, Google and Stack Overflow for answers, to no avail.

Here's how my home.php file looks so far:

<?php get_header(); ?>
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var('paged' ) : '1';
$args = array(
    'post_type' => 'post',
    'orderby' => 'date',
    'posts_per_page' => 5,
    'paged' => $paged
);
$the_query = new WP_Query($args);
?>
<!-- The Main Loop is here -->
<?php
$big = 999999999; // need an unlikely integer

echo paginate_links( array(
    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format' => '%#%',
    'current' => max( 1, get_query_var('paged') ),
    'total' => $the_query->max_num_pages
) );
?>
<?php get_footer(); ?>

In my development site, I have 7 sample posts. The first page (ie the 5 most recent posts) get rendered the way I want it. But when you click one of the numbered page links, it re-directs to the proper URL format but instead of using the home.php as the template file, it instead uses the 404.php . I may be missing something here but I can't seem to figure out what.

Any help would be appreciated.

When you want to add pagination to your defaul post provided by wordpress then you have to follow below step so pagination will work.

-> Set in wp-admin >> settings >> reading set blog posts to show as 5(number you want to display posts per page).

As whatever posts_per_page you want just set it.Hope this helps.

Replace with the pagination code below:

<div class="pagination">
    <?php 
        echo paginate_links( array(
            'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
            'total'        => $query->max_num_pages,
            'current'      => max( 1, get_query_var( 'paged' ) ),
            'format'       => '?paged=%#%',
            'show_all'     => false,
            'type'         => 'plain',
            'end_size'     => 2,
            'mid_size'     => 1,
            'prev_next'    => true,
            'prev_text'    => sprintf( '<i></i> %1$s', __( 'Newer Posts', 'text-domain' ) ),
            'next_text'    => sprintf( '%1$s <i></i>', __( 'Older Posts', 'text-domain' ) ),
            'add_args'     => false,
            'add_fragment' => '',
        ) );
    ?>
</div>

WordPress comes with a handy function called paginate_links() which does the heavy lifting. In the example above, the custom WP_Query object $query is used instead of the global $wp_query object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM