简体   繁体   中英

definitive get_posts / paginate_links

Can a Wordpress expert confirm - is there a simple, elegant, Wordpress-native way in which get_posts() queries can be paginated? I have tried to piece together how to do it from various posts, but can't seem to get it to work.

I often use get_posts() for querying my Custom Post types - but if I can't easily paginate these I may just drop get_posts() and get into the habit of using wp_query() for Custom POst Types.

What is wrong with my code? I have struggled through many PHP problems, but would still consider myself a novice.

Trying for the simplest clearest option here so I can understand how it works, use it as a template for future projects.

<div class="content-primary">
    <?php 
    $paged = ( get_query_var( 'paged' ) ) ? get_query_var(     'paged' ) : 1;
    $query_args = array(
        'post_type' => 'project',
        'posts_per_page' => 10,
        'paged' => $paged
        );

        $query_custom_posts = get_posts( $query_args );
        foreach ( $query_custom_posts as $post ) :     setup_postdata( $post ); ?>
            <article>
                    <a href="<?php the_permalink(); ?>">
                        <?php if ( has_post_thumbnail() ) :     the_post_thumbnail( 'thumbnail' );     endif;?>
                        <h3><?php the_title(); ?></h3>
                    </a>
                    <div><?php the_date(); ?></div>
                    <div><?php the_excerpt(); ?></div>
            </article>
        <?php endforeach; ?>

        <?php
        global $query_args;

        $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' => $query_args->max_num_pages
        ) );
        ?>

    <?php wp_reset_postdata();?>


</div>

I really hoped this would work, though I am aware of errors in it - I know my $query_args contains no max_num_pages.

Would be nice to have the optional use of the Wordpress next_posts_link() / previous_posts_link() too, rather than paginate_links(), but not sure if this can be made to work with get_posts().

You simply need to add the following line:

<?php query_posts('post_type=post&paged='. get_query_var('paged')); ?>

just before your get_posts() loop starts.

Full article here: http://blog.onireon.it/wordpress-get_posts-and-pagination-posts-are-correctly-displayed-but-no-pagination-links-are-showing/

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