John Davidson

php - Add section after 4 posts in wordpress

0 comments
Message:


I'm trying to figure out if there's a way to add a section of text after 4 posts on my index.php page? And then again at 8 posts.


I've only got a simple loop at the moment and haven't known where to start! Thanks


<?php
get_header();
?>

<main id="primary" class="site-main">

<div class="intro">
<h1 class="intro-text">Hi! I’m an Aussie illustrator living in London.</h1>
</div>

<div class="post-grid grid">
<div class="grid-sizer">
<?php
if ( have_posts() ) :


/* Start the Loop */
while ( have_posts() ) :
the_post();

get_template_part( 'template-parts/content-thumb', get_post_type() );

endwhile;

the_posts_navigation();

else :

get_template_part( 'template-parts/content', 'none' );

endif;
?>
</div>
</div>


</main><!-- #main -->

<?php
get_footer();


My Answer:
You can achieve this by using the `current_post` property of the WordPress loop. Here's an example code snippet that you can add to your `index.php` file:

php
if ( have_posts() ) :
$count = 0;
while ( have_posts() ) : the_post();
// Your post content here

$count++;
if ( $count == 4 ) {
echo '
Your section content after 4 posts
';
} elseif ( $count == 8 ) {
echo '
Your section content after 8 posts
';
}
endwhile;
endif;
?>


In this code snippet, we're using a `$count` variable to keep track of the number of posts that have been displayed. After every 4th post, we're adding a section with the class `section-after-4-posts`, and after every 8th post, we're adding a section with the class `section-after-8-posts`.

You can style these sections using CSS by targeting the respective classes. Just make sure to adjust the HTML structure and styling according to your needs.

Rate this post

3 of 5 based on 5181 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us