Wordpress-分页不适用于自定义循环,但可用于博客页面

时间:2019-05-23 15:09:35

标签: php wordpress pagination

我有一个具有自定义帖子类型的循环,并且没有出现分页,当我使用/ page / 2,/ page / 3输入URL时,它可以正确显示内容,但是链接不会显示在页面上页面。

代码如下:

<?php 
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$parent_only_query = new WP_Query(array(
    'post_type' => 'my_cpt',
    'posts_per_page' => 4,
    'paged' => $paged,
    'post_parent' => 0 
));

while ($parent_only_query->have_posts()){
    $parent_only_query->the_post();

//content

}       
pagination(); ?>

具有分页功能的存档页面:     

<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>

<?php //content ?>

<?php endwhile; ?>

<?php else : ?>

<?php get_template_part( 'loop-templates/content', 'none' ); ?>

<?php endif; ?>
<?php pagination(); ?>

2 个答案:

答案 0 :(得分:0)

add this in your functions.php

function pagination_nav() {
    global $wp_query;
 
    if ( $wp_query->max_num_pages > 1 ) { ?>
        <nav class="pagination" role="navigation">
            <div class="nav-previous"><?php next_posts_link( '&larr; Older posts' ); ?></div>
            <div class="nav-next"><?php previous_posts_link( 'Newer posts &rarr;' ); ?></div>
        </nav>
<?php }
}

display on page.php

<?php pagination_nav(); ?>

答案 1 :(得分:0)

分页可以显示在自定义帖子类型存档模板和自定义模板中。

存档模板的分页。

    // current page
   $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;


    // prepare arguments
   $args = array( 'post_type' => 'product',
    'post_type' => 'my_cpt',
    'posts_per_page' => 4,
    'paged' => $paged,
    'post_parent' => 0 
   );


    //prepare query
    new WP_Query( $args ); 

        // Call pagination function before wp_reset_postdata()
        the_posts_pagination( array(
            'prev_text'          => '<span class="fa fa-angle-left" aria-hidden="true"></span>',
            'next_text'          => '<span class="fa fa-angle-right" aria-hidden="true"></span>',
            'screen_reader_text' => '&nbsp;',
            'before_page_number' => '',
            'mid_size'    => 3,
        ) );

自定义模板的分页

    // Get current page.
    $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;


    // prepare arguments
    $args = array( 
     post_type' => 'my_cpt',
     'posts_per_page' => 4,
     'paged' => $paged,
     'post_parent' => 0 
   );


    //prepare query
    $query = new WP_Query( $args );
    $totalPage=$query->max_num_pages;



    $big = 999999999; // need an unlikely integer
    echo paginate_links( array(
         'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
         'format' => '?paged=%#%',
         'current' => max( 1, get_query_var('paged') ),
         'total' => $totalPage
     ) );

您可以在Wordpress Codex上查看WordPress官方文档