I"m running multiple loops on a page and on one of the loops I need to add a class to the first post that way I can offset the margin. How can I add a class to the first post from the wp_query?
<?php $my_query = new WP_Query('category_name=news&posts_per_page=3');
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate[] = $post->ID ?>
<div class="post-container">
</div>
<?php endwhile; ?>
I need to add the class to the main div container which has the class "post-container".
Thank you the fix below works perfect but what do I do if I want to use it for a normal loop instead of a wp_query? like this
<?php query_posts(array('showposts' => 3, 'post__not_in'=>$do_not_duplicate));
if (have_posts()) : while (have_posts()) : the_post(); ?>
Maybe this can help:
$first = false;
if( $my_query->current_post == 0 && !is_paged() ) { $first = true; }
And then your line with you do this:
<div class="post-container <?= ($first ? 'classname' : ''); ?>">
Not tested for syntax errors.
So try this:
<?php
$first = true;
query_posts(array('showposts' => 3, 'post__not_in'=>$do_not_duplicate));
if (have_posts()) {
while (have_posts()) {
the_post();
echo '<div class="post-container '.($first ? 'classname' : '').'"></div>';
if ($first) {
$first = false;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.