Sign in


Sign up


Dynamic carousel post loading

by Dawid Adach,

Final result preview
Live preview

1. Let's copy following MDB carousel code to our index.php file between header and footer:


<!--Carousel Wrapper-->
<div id="carousel-example-3" class="carousel slide carousel-fade white-text" data-ride="carousel" data-interval="false">
    <!--Indicators-->
    <ol class="carousel-indicators">
        <li data-target="#carousel-example-3" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-3" data-slide-to="1"></li>
        <li data-target="#carousel-example-3" data-slide-to="2"></li>
    </ol>
    <!--/.Indicators-->

    <!--Slides-->
    <div class="carousel-inner" role="listbox">

        <!-- First slide -->
        <div class="carousel-item active view hm-black-light" style="background-image: url('https://mdbootstrap.com/img/Photos/Others/img (43).jpg'); background-repeat: no-repeat; background-size: cover;">

            <!-- Caption -->
            <div class="full-bg-img flex-center white-text">
                <ul class="animated fadeInUp col-md-12">
                    <li>
                        <h1 class="h1-responsive flex-item font-bold">Material Design for Bootstrap 4</h1>
                        <li>
                            <p class="flex-item">The most powerful and free UI KIT for Bootstrap</p>
                        </li>
                        <li>
                            <a target="_blank" href="https://mdbootstrap.com/getting-started/" class="btn btn-primary btn-lg flex-item" rel="nofollow">Sign up!</a>
                        </li>
                        <li>
                            <a target="_blank" href="https://mdbootstrap.com/material-design-for-bootstrap/" class="btn btn-secondary btn-lg flex-item" rel="nofollow">Learn more</a>
                        </li>
                </ul>
            </div>
            <!-- /.Caption -->

        </div>
        <!-- /.First slide -->

        <!-- Second slide -->
        <div class="carousel-item view hm-black-light" style="background-image: url('https://mdbootstrap.com/img/Photos/Others/img%20(40).jpg'); background-repeat: no-repeat; background-size: cover;">

            <!-- Caption -->
            <div class="full-bg-img flex-center white-text">
                <ul class="animated fadeInUp col-md-12">
                    <li>
                        <h1 class="h1-responsive">Lots of tutorials at your disposal</h1>
                    </li>
                    <li>
                        <p class="my-4">And all of them are FREE!</p>
                    </li>
                    <li>
                        <a target="_blank" href="https://mdbootstrap.com/bootstrap-tutorial/" class="btn btn-primary btn-lg" rel="nofollow">Start learning</a>
                    </li>
                </ul>
            </div>
            <!-- /.Caption -->

        </div>
        <!-- /.Second slide -->

        <!-- Third slide -->
        <div class="carousel-item view hm-black-light" style="background-image: url('https://mdbootstrap.com/img/Photos/Horizontal/Nature/full%20page/img%20(24).jpg'); background-repeat: no-repeat; background-size: cover;">

            <!-- Caption -->
            <div class="full-bg-img flex-center white-text">
                <ul class="animated fadeInUp col-md-12">
                    <li>
                        <h1 class="h1-responsive">Visit our support forum</h1></li>
                    <li>
                        <p class="my-4">Our community can help you with any question</p>
                    </li>
                    <li>
                        <a target="_blank" href="https://mdbootstrap.com/forums/forum/support/" class="btn btn-default btn-lg" rel="nofollow">Support forum</a>
                    </li>
                </ul>
            </div>
            <!-- /.Caption -->

        </div>
        <!-- /.Third slide -->
        
    </div>
    <!--/.Slides-->

    <!--Controls-->
    <a class="carousel-control-prev" href="#carousel-example-3" role="button" data-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next" href="#carousel-example-3" role="button" data-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
    </a>
    <!--/.Controls-->
</div>
<!--/.Carousel Wrapper-->
              

Great!, our carousel is visible and contains 3 sample slides, though the data in it are hardcoded.

2. Replace static slides with dynamic content from posts. Replace static slides code, so everything between:


<!-- First slide -->
.
.
.
<!--/.Third slide-->
              
with following code:

<!--Dynamic query listing posts from "carousel" category-->
<?php 
$counter = 1;
$args = array(
    'orderby'          => 'date',
    'order'            => 'ASC',
    'posts_per_page'   => 3,
    'category_name'  => 'carousel'
    );

// The Query
$query1 = new WP_Query( $args );

if ( $query1->have_posts() ) {
    // The Loop
    while ( $query1->have_posts() ) {
        $query1->the_post();
        ?>
        <!-- Looping slide -->
        <div class="carousel-item view hm-black-light <?php echo $counter==1 ? "active": ""; ?>" style="background-image: url('<?php echo the_post_thumbnail_url();?>'); background-repeat: no-repeat; background-size: cover;">
            <!-- Caption -->
            <div class="full-bg-img flex-center white-text">
                <ul class="animated fadeIn col-md-12">
                    <li>
                        <h1 class="h1-responsive"><?php  echo get_the_title(); ?></h1>
                    </li>
                    <li>
                        <p><?php echo get_the_excerpt();?></p>
                    </li>
                    <li>
                        <a href="<?php echo get_permalink() ?>" class="btn btn-lg btn-elegant " rel="nofollow">Read more!</a>
                    </li>
                </ul>
            </div>
            <!-- /.Caption -->
        </div>
        <!--/.Looping slide-->
        <?php
        $counter++;
    }
    wp_reset_postdata();
} ?>
<!--/.Dynamic query listing posts from "carousel" category-->
                      

Now our slides are dynamic. Before we will analyze our new code line by line let's briefly describe what happening with our carousel now. We have replaced our static HTML code with WP Query, which loads most recent posts from a category called Carousel and sorting them in Ascending order. Now let's have a closer look on how it works:

a) $counter = 1; we are initializing counter with value 1. We will use it later to make sure that only first slide has the active class assigned.

b) Following array defines our query parameters:


$args = array(
'orderby'          => 'date',
'order'            => 'ASC',
'posts_per_page'   => 3,
'category_name'  => 'carousel'
);
            

c) Following code block is the main loop which is looping as many times as posts matched our criteria. Check comments below to find more information about each line <


        //create new query (we use number to distinguish since we will have another query for cards) using $args array
       $query1 = new WP_Query( $args );

        //check if query returns any posts
        if ( $query1->have_posts() ) {
            // query throughout all posts
            while ( $query1->have_posts() ) {
                $query1->the_post();
                ...
                //increase counter with every loop
                $counter++;
            }
            wp_reset_postdata();
        } 
        

d) Within the loop we are inserting elements like title, feature image, permalink and excerpt. We have described how to do that in lesson I-5.


<!-- Looping slide -->
<div class="carousel-item view hm-black-light <?php echo $counter==1 ? "active": ""; ?>" style="background-image: url('<?php echo the_post_thumbnail_url();?>'); background-repeat: no-repeat; background-size: cover;">
    <!-- Caption -->
    <div class="full-bg-img flex-center white-text">
        <ul class="animated fadeIn col-md-12">
            <li>
                <h1 class="h1-responsive"><?php  echo get_the_title(); ?></h1>
            </li>
            <li>
                <p><?php echo get_the_excerpt();?></p>
            </li>
            <li>
                <a href="<?php echo get_permalink() ?>" class="btn btn-lg" rel="nofollow">Read more!</a>
            </li>
        </ul>
    </div>
    <!-- /.Caption -->
</div>
<!--/.Looping slide-->
                

We are done with the carousel. Your carousel home sited is ready. You can now start next tutorial where we will extend our website with extra posts.


If something doesn’t work as expected, you can download a final code for this lesson here:

Previous Lesson Download Live preview

Do you want to share?

Facebook Twitter Google +

About author


Dawid Adach

For more than 5 years Dawid was working as an IT Consultant specializing in SOA/EAI/ESB for banking domain. He was gaining experience working in countries like Netherlands, Belgium, Poland and India developing enterprise class systems for the biggest companies within domain. Currently, Dawid's main focus is design & web development. He designs and develop websites using Adobe Photoshop, HTML5 / CSS3, bootstrap, JS, Meteor, AJAX, PHP and SQL.

Comments 6

Leave a reply

BrandFlow - Marketing Automation for Bootstrap

Powerful and free software which will automate your Bootstrap project.

Modals creator, scoring system, tag manager & analytics dashboard included in one tool.

Created by MDB Team.

Learn more