0

Is it possible to add some html after a set amount of posts?

For the purposes of a slider after 6 posts i need it to enclose in a div/li or whatever then start a new div/li for the next 6 and so on.

Here is my custom query which just prints the post name in a list.

<ul>

<?php $args=array('post_type' => 'courses','post_status' => 'publish','posts_per_page' => -1);$my_query = null;$my_query = new WP_Query($args);if( $my_query->have_posts() ) {while ($my_query->have_posts()) : $my_query->the_post(); ?>   

<li><h2><?php the_title(); ?></h2></li> 

<?php endwhile;} wp_reset_query();?> 

</ul>

After at the start and end of 6 posts i need to open a div then close it after the 6th post.

Is this possible with WordPress PHP?

Many thanks for any help :)

2 Answers 2

1

Here's one way of doing it:

<?php
$courses = get_posts( array(
    'post_type' => 'courses',
    'posts_per_page' => -1
    ) );

if ( $courses ) {
    print "\n" . '<div style="background:pink">';
    foreach ( $courses as $course_count => $post ) {
        setup_postdata( $post );
        the_title( "\n", '<br>' );
        if ( 5 == $course_count ) {
            print "\n" . '</div>';
            print "\n" . '<div style="background:yellow;">';
        }
    }
    print "\n" . '</div>';
}

wp_reset_postdata();
?>
0

a possible way:

<ul>  
<?php $args=array('post_type' => 'courses','post_status' => 'publish','posts_per_page' => -1);$my_query = null;
$my_query = null;
$my_query = new WP_Query($args);
    $count = 0; //initialize count variable    
    if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?>      
        <?php if( $count%6 == 0 ) { ?>OUTPUT OPENING HTML TAG<?php } ?>       
    <li><h2><?php the_title(); ?></h2></li>    
        <?php if( $count%6 == 5 ) { ?>OUTPUT CLOSING HTML TAG<?php } ?>
        <?php $count++; ?>       
    <?php endwhile; }  ?>    
        <?php if( $count%6 != 0 ) { ?>OUTPUT CLOSING HTML TAG<?php } // in case there is not a multiple of 6 posts ?>       
<?php wp_reset_query();?>   
</ul> 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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