简体   繁体   中英

Wordpress custom wp_query archive page 2 not found

I have a custom WP_Query to for archive.php. I have fixed the pagination issue I was having by following this great answer here . And I'm using this answer from here to help me find the category without having to define each category.

I need to use wp_query as I'm changing layouts and inserting different content after X amounts of posts. However I have removed all of this whilst testing the pagination.

When I use the pagination to go to /page/2/ it says 'Page not found'. I thought this would be a simple permalink update. I've gone into my permalink settings multiple times and re-saved them but it hasn't fixed the page not found issue.

Below is my code. I'm not sure if there is something in this thats causing the issue.

<?php
global $query_string;

$query_args = explode("&", $query_string);

// Define custom query parameters
$archive_query = array(
    'posts_per_page'=> 3
);

// Get current page and append to custom query parameters array
$archive_query['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

foreach($query_args as $key => $string) {
    $query_split = explode("=", $string);
    $archive_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach


// Instantiate custom query
$query = new WP_Query($archive_query);

// Pagination fix
$temp_query = $wp_query;
$wp_query   = NULL;
$wp_query   = $query;



    // Output custom query loop
if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();?>

        <h1><?php the_title();?></h1>    

    <?php endwhile;
endif;
wp_reset_postdata();

?>

<div id="pagination-wrapper">
    <?php 
        previous_posts_link( 'Older Posts' , $query->max_num_pages  );
        next_posts_link( 'Newer Posts', $query->max_num_pages ); 
    ?>

</div>
<?php
// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query; 
?>

If you aren't using the main loop I think it would be easier changing it rather then creating a new query and dealing with it.

You could add

function alter_category_posts_per_page( $query ) {
    if ( $query->is_category() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', '3' );
    }
}
add_action( 'pre_get_posts', 'alter_category_posts_per_page' );

to your theme functions.php to achieve that.

If it doesn't work at all you probably have some content using the same slug as the category.

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