How to add padding between posts
-
18-01-2021 - |
Question
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>
Solution
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>
OTHER TIPS
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;
}