get_posts not working as expected

I’m trying to get posts from 3 different categories and list them on the front page:

  // Carousel articles
  $args = array( 'numberposts' => 3, 'orderby' => 'date', 'category' => 'karusell' );
  $carousel = get_posts($args);

  // News articles
  $args = array( 'numberposts' => 3, 'orderby' => 'date', 'category' => 'nyheter' );
  $news = get_posts($args);

  // Featured articles - max 2 posts
  $args = array( 'numberposts' => 2, 'orderby' => 'date', 'category' => 'feature' );
  $featured_posts = get_posts($args);

Then I output them by doing this:

Read More
foreach( $carousel as $post ) : setup_postdata($post);
 // code here
endforeach;

My problem is that all my loops outputs the same posts. Am I using the wrong function for getting posts?

I could use something like this:

query_posts("category_name=feature&posts_per_page=2&orderby=date");
while (have_posts()) : the_post();
//code
endwhile;

But I was hoping I could fetch all the articles at the top of my code and not “inline”.

Related posts

Leave a Reply

2 comments

  1. With get_posts(), try using the category ID instead of the category slug.

    For example:

    // Carousel articles
    $args = array( 'numberposts' => 3, 'orderby' => 'date', 'category' => 1 );
    $carousel = get_posts($args);
    
    // News articles  
    $args = array( 'numberposts' => 3, 'orderby' => 'date', 'category' => 2 );
    $news = get_posts($args);
    
    // Featured articles - max 2 posts
    $args = array( 'numberposts' => 2, 'orderby' => 'date', 'category' => 3 );
    $featured_posts = get_posts($args);
    
  2. Here is another possible solution :

    $args = array(
        'post_type' => 'post',        
        'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => 'karusell'
        )
    ));
    $posts = get_posts( $args );