0

I want to run the loop so that it retrieves posts from only one particular category AND outputs only 4 posts AND excludes the latest one.

To query only one category, I found this:

<?php query_posts('cat=1'); ?> 
<?php if ( have_posts() ) : while (have_posts() ) : the_post(); ?> 
<?php the_content(); ?> 
<?php endwhile; endif; ?>

And to exclude the latest post and output only 4 posts, I found this:

<?php query_posts('posts_per_page=4&offset=1'); ?> 
<?php if (have_posts() ) : while ( have_posts() ) : the_post(); ?> 
<?php the_content(); ?> 
<?php endwhile; endif; ?>

However, I don't know how to combine the two. Can I do that, or is there a better way?

1
  • 1
    Note: It's recommended to us WP_Query() (Rishabh's post) than query_posts(). query_posts() is dirty function.
    – user94212
    Commented May 21, 2016 at 11:42

1 Answer 1

0

Try this code

global $myOffset;
$myOffset = 1;
$paged = get_query_var('paged') ? get_query_var('paged') : 1; //Use 'page' instead of 'paged' if you are on home page

$args = array(
    'post_type' => 'post',
    'cat'=> 1,    //Selecting post category by ID to show
    'posts_per_page' => 4,  //No. of posts to show
    'offset' => $myOffset,  //Eexcluding latest post
    'paged' => $paged       //For pagination
);

$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();
    the_content(__('Continue Reading'));             
endwhile;
2
  • It would be better if you will explain your code a bit!
    – Sumit
    Commented May 21, 2016 at 15:42
  • Hi Sumit! sry for late reply.. Code has been updated with explanation :-)
    – Rishabh
    Commented May 23, 2016 at 6:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.