Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an offset to a category loop in WordPress

Tags:

php

wordpress

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!

like image 944
user28240 Avatar asked Feb 14 '23 01:02

user28240


1 Answers

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.

like image 139
Rahil Wazir Avatar answered Feb 23 '23 14:02

Rahil Wazir