Adding an offset to a category loop in WordPress

2019-05-10 06:45发布

In category.php of a WordPress theme, you have the following loop:

if ( have_posts() ) : while ( have_posts() ) : the_post(); 
// output posts
endwhile; endif;

How do you go abouts outputting this exact same loop but with an offset? I found that you can change the loop by doing a

query_posts('offset=4');

But this resets the entire loop and the offset works but shows all the posts from every category, so I get the impression the query_posts completely resets the loop and does it with only the filter you add. Is there a way to tell the loop:

"do exactly what you're doing, except the offset make it 4"

Is this possible?

Thanks!

标签: php wordpress
1条回答
我命由我不由天
2楼-- · 2019-05-10 07:13

First of all don't use query_posts() see here instead use WP_Query

Try this:

//To retrieve current category id dynamically
$current_cat = get_the_category();
$cat_ID = $current_cat[0]->cat_ID;

$loop = new WP_Query(array(
    'offset' => 4,         //Set your offset
    'cat' => $cat_ID,      //The category id
));

if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); 
// output posts
endwhile; endif;

Yes as Wordpress stated:

Setting the offset parameter overrides/ignores the paged parameter and breaks pagination (Click here for a workaround)

Just follow the pagination workaround instructions and you're good to go.

查看更多
登录 后发表回答