If you're more comfortable with arrays, you can always make use of the get_posts()
function instead, which takes arguments (almost) exactly like the WP_Query()
Class. get_posts()
actually makes use of WP_Query
as well.
That said, your code wouldn't be all that difficult to modify with "native PHP" as you mentioned. It's just a while
loop instead of a foreach
loop, both of which are similar control structures.
All you have to do is add a counter variable and increment it after each pass using the increment operator: ++
;
Here's a quick code sample for you:
$args = array(
'posts_per_page' => 2,
);
$query = new WP_Query( $args );
if( $query->have_posts() ){
$count = 0; // Start a Counter
while( $query->have_posts() ){
$query->the_post();
printf( '<div class="post float-%s">', ($count++ % 2 == 0) ? 'left' : 'right' ); // If counter is odd: "left", even: "right"
printf( '<h4 class="post-title">%s</h4>', get_the_title() );
the_content();
echo '</div>';
}
} else {
echo 'No Posts Found.';
}
A couple of things:
I moved the $args
array to its own variable. Some queries can get pretty complex, having them as a designated variable can improve long-term maintainability.
You also don't need the post_type
argument if you just want post
, because that's the default value.
I added an if
clause, so if your posts ever disappeared or you moved this code, there'd be a fall back for "nothing found".
I used a bit of a complex Ternary Operator in the post class. I increment it there so we don't need another line to increment the $count
later, and it removes the need for a multi-line "if/else" to determine left
or right
.
Beyond that, you didn't provide a markup structure so I made use of a the_
and get_the_
function if you're unaware of the difference.