php – Binding a css class to the first news in a loop, on the wordpress engine

Question:

The loop specifies the class for all news that will be displayed. I took a template where the post1 class goes to the first news:

<div id="post-1" class="post1">

It is necessary that the post class is displayed for the following news:

<div id="post-2" class="post">
<div id="post-3" class="post">

If you define a function in functions.php :

<?php //свой класс у первой записи в цикле start
function wph_first_post_in_query($classes) {
    global $wp_query;
    if (0 == $wp_query->current_post) {
        $classes[] = 'first';
    }
    return $classes;
}
add_filter('post_class', 'wph_first_post_in_query');
//свой класс у первой записи в цикле end
?>

and instead of <div class="post" id="post"> set the function wp <div <?php post_class() ?> id="<?php the_ID(); ?>"> , I can set a separate style for the first news, but the problem is that the style is applied to all news in full, and then to the first separately. I need the first news to have a completely different style.

Answer:

You can simply enter a counter into the post display loop, by the value of which you can determine which post you are displaying.

<?php
if (have_posts()) {
    $i = 0;
    while (have_posts()) {
        the_post();
        ?>
        <div class="<?php echo $i == 0 ? 'post1' : 'post'; ?>">...</div>
        <?php

        $i++; //не забывайте про инкремент счётчика в каждой итерации
    }
}

Update for a particular case:

<?php if (have_posts()) : $i = 0; ?>
    <?php while (have_posts()) : the_post();  ?>
        <div class="<?php echo $i == 0 ? 'post1' : 'post'; ?>" id="post"> контент </div>
    <?php $i++; endwhile; ?>
    <div class="pagenavi">
        <?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?>
    </div>
    <?php else : ?>
<?php endif; ?>
Scroll to Top