How to use Bootstrap Carousel with WordPress posts Loop

by Carla Goncalves
on July 1, 2019
Frontend, WordPress, Bootstrap, PHP

It is unavoidable to not use the Bootstrap carousel if you are using bootstrap in your pages. When using it with WordPress can be a bit tricky to make it work dynamically with your WP data. I noticed this is a recurrent problem with the same question being asked many times on stackoverflow. In the end it’s quite an easy solution. The tricky part for me was to get the active class working properly. For that I used the ternary logic and voilà.

Working example :

		 <!-- carousel start -->
         <div class="carousel slide" data-ride="carousel" id="carouselExampleIndicators">
            <div class="carousel-inner">
            <?php

                /* Start the Loop */
                $args = array( 'numberposts' => 3, 'orderby' => 'date' );

                $postslist = get_posts( $args );

                if( count($postslist) ):

                    $i = 0;

                foreach ($postslist as $post) :  setup_postdata($post);


                $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large');

                list($url, $width, $height, $is_intermediate) = $thumbnail;

                    ?> 
                <div class="carousel-item <?php echo $i == 0 ? ' active': ''; $i++; ?>" >

                    <img alt="First slide" class="d-block w-100" src="<?php echo $url; ?>">

                    <a href="<?php echo get_the_permalink($page->ID); ?>" class="btn bg-pink text-center mx-0">Go Somewhere</a>

                    <h5 class="card-title text-white"><?php  the_title(); ?> </i></h5>

                </div>

                <?php 
            
                endforeach;

             endif;
             ?>

               
            </div>
        </div>
    <!-- carousel end -->

Bootstrap Carousel with Wordpress Loop - Desktop


You might want to read...
DailyUI,Css Daily UI #2- Image scrolling on hover

Scrolling hover effect Images - Css only...

DailyUI Daily UI - Rethinking the user experience #1

Transitions, delays, gradients, Jquery and et al....

WordPress/Bootstrap How to use Bootstrap Carousel with WordPress posts Loop

Bootstrap can be a bit tricky to make it work dynamically with your WP data...