Reputation: 199
OK, I creating homepage that have 4 latest posts, and each of them must have different class to style them using CSS.
I am using this code to display 4 latest posts:
<?php
// the query
$the_query = new WP_Query( array(
'category_name' => 'artykuly',
'posts_per_page' => 4,
'order' => 'ASC',
));
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<!---posty home--->
<div class="home-posty" style="background: #ccc; margin: 20px;">
<a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title(); ?></a>
<div class="home-post-opis">
<?php the_excerpt(); ?>
</div>
<div class="home-post-tags">
<?php the_tags(); ?>
</div>
<div class="home-post-date">
<?php echo get_the_date(); ?>
</div>
</div>
Question is how to set for lates 4 post different class like: "first-post", "second-one", "third-post", "last-one". It can't be post-id or title because every new post will have different ID and layout must be always the same. How to force adding my own classes to them? I was thinking about CSS nth-child but custom classess will be better IMHO.
I also need to wrap (using DIV) first two of them. Is it possible?
Upvotes: 0
Views: 307
Reputation:
Please, use add_filter
to change the classes list. and add_action
for wrapping
add_filter('prefix_home_posts_classes', 'prefix_home_posts_classes', 10, 2);
function prefix_home_posts_classes( $classes, $index ) {
$post_order = $index % 4;
switch ( $post_order ) {
case 0:
$classes[] = 'last-one';
break;
case 3:
$classes[] = 'third-post';
break;
case 2:
$classes[] = 'second-one';
break;
case 1:
$classes[] = 'first-post';
break;
}
return $classes;
}
add_action('prefix_home_before_post', 'prefix_home_before_post');
add_action('prefix_home_after_post', 'prefix_home_after_post');
function prefix_home_before_post( $index ) {
if ($index === 1) {
echo '<div class="wrapper">';
}
}
function prefix_home_after_post( $index ) {
if ($index === 2) {
echo '</div>';
}
}
And your HTML template, please change to this one
$index = 0; ?>
<?php if ($the_query->have_posts()) { ?>
<?php while ($the_query->have_posts()) { ?>
<?php $the_query->the_post(); ?>
<?php $index++; ?>
<?php $post_classes = apply_filters('prefix_home_posts_classes', ['home-posty'], $index); ?>
<?php $post_classes_string = implode(' ', $post_classes); ?>
<?php do_action( 'prefix_home_before_post', $index ); ?>
<div class="<?php echo esc_attr($post_classes_string); ?>" style="background: #ccc; margin: 20px;">
<a href="<?php echo esc_url(get_permalink()); ?>"><?php the_title(); ?></a>
<div class="home-post-opis">
<?php the_excerpt(); ?>
</div>
<div class="home-post-tags">
<?php the_tags(); ?>
</div>
<div class="home-post-date">
<?php echo get_the_date(); ?>
</div>
</div>
<?php do_action( 'prefix_home_after_post', $index ); ?>
<?php } ?>
<?php } ?>
Upvotes: 1