自定义 post 类型的存档分页不适用于 woo canvas 子主题

Custom post type archive pagination doesn't work on woo canvas child theme

我正在为 woo canvas 构建一个子主题,我正在努力让我的分页在我的存档页面上工作,以用于一个名为 book 的新自定义 post 类型。

post类型注册码如下:

$args = array(
    'labels'             => $labels,
    'public'             => true,
    'publicly_queryable' => true,
    'show_ui'            => true,
    'show_in_menu'       => true,
    'query_var'          => true,
    'rewrite'            => array( 'slug' => 'book' ),
    'capability_type'    => 'post',
    'has_archive'        => true,
    'hierarchical'       => false,
    'menu_position'      => null,
    'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
    );

register_post_type( 'book', $args );

它在我的函数文件中并且工作正常。

我的存档中有以下代码-book.php 它显示了分页链接,但每当我导航到分页页面时都会给我一个 404 错误,例如- http://localhost/wp/book/page/2/ :

<?php

global $wp_query, $woo_options, $paged, $page, $post;
?>
<?php get_header(); ?>
<?php

$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

$args = array(
    'post_type' => 'book',
    'paged' => $paged,
    'posts_per_page' => 3
    );
$query = new WP_Query( $args );
while ( $query->have_posts() ) { $query->the_post(); ?>
<?php echo the_title(); ?>
<?php } ?>
<?php 
woo_pagenav( $query );
wp_reset_query();
get_footer(); ?>

我已将永久链接设置为 'Post name' 并多次刷新永久链接,同时选择了 Post 名称和默认永久链接。

第二页不存在,因此永远不会加载您的存档模板。每页的默认帖子数将用于初始查询,在这种情况下没有第二页帖子。

例如,如果您在自定义查询下有 5 个书帖,则第一页将显示 3 个,第二页将显示 2 个。在默认的每页帖子数 (10) 下,所有 5 个都将显示在第一页上,然后不需要第 2 页。然后 WordPress 加载 404 模板。

您需要使用 pre_get_posts 钩子来修改主查询。

示例:

/**
 * Change the number of posts per page on the book archive.
 *
 * @param object $query
 */
function wpse_modify_book_archive_query( $query ) {

    // Only apply to the main loop on the frontend.
    if ( is_admin() || ! $query->is_main_query() {
        return false;
    } 

    // Check we're viewing the book archives.
    if ( $query->is_post_type_archive( 'book' ) ) {
        $query->set( 'posts_per_page', 3 );
    }
}
add_action( 'pre_get_posts', 'wpse_modify_book_archive_query' );