Ecommerce Shopify WordPress Discussion

Render three or two posts in each slide alternately in a Swiper slider

I'm developing a WordPress plugin that renders a slider using the Swiper lib. I need to show three posts (odd slides) or two posts (even slides) in each slide alternately. This is the code I came up but it's not working as I expect to: $posts = get_posts( $args ); $html = '<!-- Begin slider markup --> <div class="swiper"> <div class="swiper-wrapper">'; // Counter to keep track of the posts $post_counter = 0; $posts_per_slide = 3; foreach ( $posts as $post ) { // Start a new slide after every three or two posts if ( $post_counter % $posts_per_slide === 0 ) { $html .= '<div class="swiper-slide">'; } $html .= '<article id="post-' . esc_attr( $post->ID ) . '" class="wp-post"> <div class="wp-post-thumbnail"> <a href="' . esc_url( get_the_permalink( $post->ID ) ) . '"><img src="https://placehold.co/1000x700" width="1000" height="700" /></a> <h2 class="wp-post-title">' . get_the_title( $post->ID ) . '</h2> </div> </article>'; // Increment the post counter $post_counter++; // Close the slide after every three or two posts if ( $post_counter % $posts_per_slide === 0 ) { $html .= '</div>'; $posts_per_slide = ( $posts_per_slide === 3 ) ? 2 : 3; } } $html .= '</div> </div> <!-- End slider markup -->'; echo $html; Any ideas?
You aren't resetting your post counter in your second if ( $post_counter % $posts_per_slide === 0 ) {} block. On first loop, you open the swiper_slide div, make the article, and increment $post_counter. On second loop, $post_counter is 1, incremented to 2. On third loop, $post_counter is 2, incremented to 3, which satisfies the second check, closes the swiper_slide div, and sets $posts_per_slide = 2. Your $post_counter is still set to 3. The next loop (post 4) then checks 3 % 2 === 0 which is false, and consequently doesn't open the next swiper_slide div. Reset your $post_counter each time your second check is true, and you should be good.

January 12, 2024

TurboCommerce make the better internet purchasing globaly

Turbo Multi-language Translator

Make the better internet purchasing globaly

Turbosify SEO Speed Booster

5.0 (7) Free plan available
Get better conversions by improving store loading speed Installed

Turbo Multi-language Chat - AI Customer service in one hand

TurboCommerce make the better internet purchasing globaly
Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.