WordPress pagination with get_posts?

I need to make adjustments to a horribly written WP theme that (a custom theme that was written in tables, and bad code).

The theme has several custom templates, but pagination wasn’t used and get_posts was used in place of query_posts –

Read More
    <?php query_posts('showposts=1'); ?>
    <?php $posts = get_posts('numberposts=10&offset=0&category_name=albertsons, carrs, dominicks, genuardis, heb, kroger, pavillions, publix, randalls,safeway,shop-rite,tom-thumb,vons,whole-foods'); foreach ($posts as $post) : start_wp(); ?>
    <?php static $count2 = 0; if ($count2 == "10") { break; } else { ?>

...

    <?php $count2++; } ?>
    <?php endforeach; ?>

I need to get pagination to work with get_posts, or rewrite the function to use query_posts only, so that I can add 'paged' => get_query_var('page')

When I try to rewrite to only use query_posts, the whole damn thing breaks.

Update:

<?php 
global $wp_query;

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


query_posts(array('posts_per_page' => '3','paged'=>$paged,'category_name'=>'albertsons, carrs, dominicks, genuardis, heb, kroger, pavillions, publix, randalls,safeway,shop-rite,tom-thumb,vons,whole-foods')); ?>
                    ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

Which shows the loop, but the pagination isn’t working. If I click “older posts” the url changes to page-2, but the content is exactly the same.

Related posts

Leave a Reply

1 comment

  1. This is all sorts of wrong. First don’t use start_wp(); I think that was depreciated 4 years ago. Second your loop is messy, query_posts is for altering the main loop, aka not get_posts.

    So just write it normally using get_posts or WP Query.

    $args = array( 'numberposts' => 1, 
                   'offset'=> 0, 
                   'category_name' => 'carrs, dominicks, genuardis, etc', 
                    );
    
    
    $the_query = new WP_Query( $args );
    
    while ( $the_query->have_posts() ) : $the_query->the_post();
    
    $count_posts = $the_query->current_post + 1; // use this to count your posts
    
    //your loop stuff
    endwhile;
    

    In not sure how you want your pagination to work, if you just want next/previous links use <?php previous_post(); ?> <?php next_post(); ?> for true numbered pagination I recommend a plugin like WP-PageNavi or WP-Paginate that easily integrated into your theme through a function.

    http://codex.wordpress.org/Class_Reference/WP_Query
    http://codex.wordpress.org/Next_and_Previous_Links