Forums

Multiple Showpost Queries (4 posts)

  1. Alkorr
    Member
    Posted 2 years ago #

    Hi, I want to show the last 3 posts from 4 different categories and to do so I have to make 4 different queries which seems to be a lot (I already make several other queries on my home page). So I would like to know if there is a way to optimize these queries.

    Here is my code:

    <table width="624" cellpadding="0" cellspacing="0" border="0">
    <tr>
    <td width="300" align="left" valign="top">

    Beach
    <?php query_posts('showposts=3&category_name=Beach'); ?>
    <?php while (have_posts()) : the_post(); ?>
    " rel="bookmark" title="Read: <?php the_title(); ?>"><?php the_title(); ?>
    <?php endwhile; ?>

    Roads
    <?php query_posts('showposts=3&category_name=Roads'); ?>
    <?php while (have_posts()) : the_post(); ?>
    " rel="bookmark" title="Read: <?php the_title(); ?>"><?php the_title(); ?>
    <?php endwhile; ?>

    <td width="24" align="center" valign="center"></td>
    </td>
    <td width="300" align="left" valign="top">

    Streets
    <?php query_posts('showposts=3&category_name=Streets'); ?>
    <?php while (have_posts()) : the_post(); ?>
    " rel="bookmark" title="Read: <?php the_title(); ?>"><?php the_title(); ?>
    <?php endwhile; ?>

    Buildings
    <?php query_posts('showposts=3&category_name=Buildings'); ?>
    <?php while (have_posts()) : the_post(); ?>
    " rel="bookmark" title="Read: <?php the_title(); ?>"><?php the_title(); ?>
    <?php endwhile; ?>

    </td>
    </tr>
    </table>

    I would also like to do the same (show the last 3 posts from 4 differents tags from the same parent category.

    Thank you for your help! :)

  2. MichaelH
    Volunteer
    Posted 2 years ago #

    Here's some sample code from Austin Matzko (filosofo), to get 5 posts in 6 different categories, that you might like:

    $post_ids = array(0);
    foreach( array(1, 2, 3, 4, 5, 6) as $cat_id ) {
            if ( $posts = get_posts(array('cat' => $cat_id, 'showposts' => 5)) ) {
                    $first = array_shift($posts);
                    $post_ids[] = $first->ID;
            }
    }
    query_posts(array('post__in' => $post_ids));
  3. Alkorr
    Member
    Posted 2 years ago #

    Thank you Michael! So with this code I only make 1 query and not 4 like with my previous code, right?

    And what about the tags? I looked at the Codex and it's not very clear to me...

    :)

  4. MichaelH
    Volunteer
    Posted 2 years ago #

    Guess you could try the tag__in argument in that get_posts code.

    Thequery_posts() article has info on tag__in but I believe you can use that argument with get_posts

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags