user10548418
user10548418

Reputation:

Execute 1 query to get 3 posts from each category

I want to get 3 posts (if exists) from each category, and execute only one query to get all posts.

For example if I have 3 categories then I want to get a total of 9 posts from all categories.

Below is how I do using a loop to execute multiple queries:

$query  = new WP_Query;

foreach ( $cats as $cat ) :
    $query->query( array(
        'cat'                 => $cat->term_id,
        'posts_per_page'      => 3,
        'no_found_rows'       => true,
        'ignore_sticky_posts' => true,
    ));

And I tried this:

    $args = array(
            'posts_per_page' => 3,
            'order'          => 'desc',
            'post_type'      => 'post',
            'cat'  => array(19,20,2,3),
            'ignore_sticky_posts' => true
        ); 
   $args['orderby'] = 'post_views';
   $posts = get_posts( $args );

I cannot figure how to get 3 posts if exists from each category or all existing categories.

As a result I get only 3 posts from first category

Upvotes: 3

Views: 1955

Answers (2)

Parthavi Patel
Parthavi Patel

Reputation: 767

<?php

    $cat_args = array (
        'orderby' => 'name',
        'order' => 'ASC',
    );

    $threecategories = get_categories( $cat_args ); 

    foreach ( $threecategories as $threecategory ) {

        echo '<a href="' . esc_url( get_category_link( $threecategory->term_id ) ) . '">' . $threecategory->name . '</a>';

        $post_args = array(
            'posts_per_page' => 3,
            'cat' => $threecategory->cat_ID
        );

        $threeposts = query_posts( $post_args );

        while(have_posts()) : the_post();

            echo '<a href="' . esc_url( get_the_permalink() ) . '">' . get_the_title(). '</a>';

        endwhile; 
    }
    wp_query_reset();

May be this will help you

Upvotes: 0

Mohamed Salem Lamiri
Mohamed Salem Lamiri

Reputation: 6077

Try the following

$args = array(
'cat'      => array(1,2,3),
'order'    => 'ASC',
'showposts' => 3
    );
query_posts($args);

Upvotes: 1

Related Questions