Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialronalinfante
12,726 PointsMultiple continuous WP_Queries?
Is there a way to have WP_Query take in arguments that would allow you to query the latest 4 posts, for example, in one div and then the next 4 in another div?
I need this behavior for a slider. If not, what are some alternatives?
3 Answers
ronalinfante
12,726 PointsI have found my solution. The offset parameter lets you skip posts before outputting them.
Anthony Moore
2,282 PointsYou could set a counter on your query and then run an if/else statement to put the posts into two separate divs.
Are you comfortable with PHP?
ronalinfante
12,726 PointsYeah I'm comfortable. How are you incorporating a counter into the query? What arguments are passing?
Anthony Moore
2,282 PointsYou can try something like this:
$custom_query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' =>'8' ) );
if ( $custom_query->have_posts() ) :
$counter = 0;
while ( $custom_query->have_posts() ) : $custom_query->the_post();
if ($counter < 4) :
echo '<div class="col-1">';
echo get_the_title();
echo '</div>';
else :
echo '<div class="col-2">';
echo get_the_title();
echo '</div>';
endif;
$counter++;
endwhile; wp_reset_postdata();
endif;
Anthony Moore
2,282 PointsYou can try something like this:
$custom_query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' =>'8' ) );
if ( $custom_query->have_posts() ) :
$counter = 0;
while ( $custom_query->have_posts() ) : $custom_query->the_post();
if ($counter < 4) :
echo '<div class="col-1">';
echo get_the_title();
echo '</div>';
else :
echo '<div class="col-2">';
echo get_the_title();
echo '</div>';
endif;
$counter++;
endwhile; wp_reset_postdata();
endif;
Anthony Moore
2,282 PointsAnthony Moore
2,282 PointsIn this situation you would be querying the database two times instead of one. It is better to do some PHP magic for this particular situation.