Reputation: 55
I am building featured posts section on my site using Wordpress tags (3 latest posts tagged as "featured" are being shown on the homepage) using this code:
<?php
$args=array(
'tag' => 'featured',
'showposts'=>3,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="featured-article">
<!--thumbnail, title and link code here -->
</div>
<?php
endwhile;
} //if ($my_query)
wp_reset_query(); // Restore global post data stomped by the_post().
?>
Every entry is wrapped with "featured-article", but since i want the first post to be full-width and other 2 half width, i was wondering how can i add appropriate classes to them? So, the first post gets "full-width" class and other two "half-width"...
I apologize if i didnt explained it properly (english not first language and all).
Any help would be greatly appreciated
Upvotes: 0
Views: 454
Reputation: 501
You can solve this with counter.
<?php
$args=array(
'tag' => 'featured',
'showposts'=>3,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
//add classes
$counter = 0;
$classes = '';
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$classes = $counter == 0 ? ' full-width' : ' half';
?>
<div class="featured-article<?php echo $classes; ?>">
<!--thumbnail, title and link code here -->
</div>
<?php
$counter++;
endwhile;
} //if ($my_query)
wp_reset_query(); // Restore global post data stomped by the_post().
?>
Or You can make a custom filed for addition class.
Upvotes: 0
Reputation: 1843
You can get the index of your post with $my_query->current_post while you're in the loop.
$class = $my_query->current_post == 0 ? 'full-width' : 'half-width';
You might also want to make sure that the class only gets applied to the first item of the first page
$class = $my_query->current_post == 0 && !is_paged() ? 'full-width' : 'half-width';
Here's your loop
<?php
$args=array(
'tag' => 'featured',
'showposts'=>3,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$class = $my_query->current_post == 0 && !is_paged() ? 'full-width' : 'half-width'; ?>
<div class="featured-article <?php echo $class; ?>">
</div>
<?php
endwhile;
} //if ($my_query)
wp_reset_query(); // Restore global post data stomped by the_post().
?>
Upvotes: 1