Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have the categories listed below in my post post type.

Category Name: Test 1 ID: 1
Category Name: Test 2 ID: 2
Category Name: Test 3 ID: 3
Category Name: Test 4 ID: 4

I'd like to retrieve for each category the latest 2 posts, except category with ID 4, with posts ordered by date. Some posts may be attached to more than one category. On each every post I would like to display also the category name. But only one category. For example if I have already listed 2 posts from Category ID #1 and the following post is attached to Category ID #2 & #1, the name of the Category ID #2 should be displayed.

I can retrieve the latest 2 posts from each category but hey are grouped into categories. Sometimes I might have the following post order depending to which categories I have attached the latest posts:

- post with ID 111 to Category ID 1
- post with ID 110 to Category ID 1
- post with ID 109 to Category ID 3
- post with ID 108 to Category ID 2
- post with ID 107 to Category ID 3
- post with ID 106 to Category ID 2

As you can see the order is NOT 1, 1, 2, 2, 3, 3. It must be ordered by the posted date.

I have tried several methods, with custom sql queries or Transient API, but without any success. Maybe I have written something wrong, which is very possible since I wanted to avoid multiple queries and having less experience with custom sql queries. I've inspired from the following tickets:

I have tried also with a for loop:

global $exclude_ids;
for ( $i = 1; $i <= 3; $i++ ) {
    if ( $i==1 ) { $cat_name = "cat-1"; }
    if ( $i==2 ) { $cat_name = "cat-2"; }
    if ( $i==3 ) { $cat_name = "cat-3"; }
    $query = 'category_name='.$cat_name.'&showposts=2';
    $recent = new WP_Query( $query );
    if ( $recent->have_posts() ) :
    while ( $recent->have_posts() ) : $recent->the_post();
    // get category name
    $category = get_the_category();
    // store id to exclude later
    $exclude_ids[] = get_the_id();
?>
    <div class="row">
        <a href="<?php the_permalink(); ?>" class="text"><?php the_title(); ?></a>
        <?php 
        // though here I need the same name as $cat_name
        echo $category[0]->cat_name;
        ?>
    </div><!-- .row -->
<?php
    endwhile;
    endif;
}

Again, the posts are grouped by categories. I'm not posting any other code here (have spent almost all the day with this), since all my tries have failed. Some good directions would be very helpful for me.

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.