0

Ultimately, I'm really confused on how exactly you create a single class that affects each post in a static home page "recent post" type content area. I want to essentially have it where there's a post with a background, a space, then the next post with the same background, but not have the background behind all the posts. I hope that makes sense. Here's the code I have, but no matter what I do, I'm only able to add a class for one post at a time with the ID.

<ul>

<?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
<div class="new_home_single"><?php the_post()?></div>

<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>


<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>


<?php the_excerpt(__('(more…)')); ?>


<?php 
endwhile;
wp_reset_postdata();
?>
</ul>
1

Wordpress already generates class for each posts, you can use these classes using the post_class function.

Note: The function can be used either within the loop or by passing the $post_id

So you would have

<ul>
    <?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>

    <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

        <div id="post-<?php the_ID(); ?>" <?php post_class( 'post' ); ?>>
            <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>

            <?php the_excerpt(__('(more…)')); ?>
        </div>

    <?php
    endwhile;
    wp_reset_postdata();
    ?>
</ul>
  • OMG Thank you sooo much!! Seriously! What's crazy is that I did this before. Guess why it didn't work? I had to empty browser cache. Which is weird because it's nothing but an underscores framework. No clue how to turn that off. – geektripp Dec 30 '16 at 3:44
0

I hope that makes sense.

Partly :) But if I've understood it right and you want to style each post excerpt you'll need a container around it that you can reference with CSS, and currently, you've got your class "new_home_single" outside the while loop, so that single class is being applied to all your post excerpts.

So the simplest change to your code is to add a wrapper around the excerpt like this:

<div class="post-excerpt">
    <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
    <?php the_excerpt(__('(more…)')); ?>
</div>

And then some CSS to style each excerpt, using margin instead of padding to have background-free space between each one:

.post-excerpt {
     background-color: #dddddd;
     margin: 2rem 0;
}
  • Thank you. It was somewhat what I asked. I know it was confusing, but this actually comes in handy later. Thank you. – geektripp Dec 30 '16 at 5:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.