Bootstrap Carousel Slider for posts, pages.

Spread the love
The beginnings of programming can be really difficult and we do not always have time to write code from scratch. Recently I searched the Internet for hours to find the right code for bootstrap carousel for wordpress, displaying not only posts but also other pages in the carousel. Finally, I found!
The below code generates a Bootstrap carousel with WordPress posts, pages with your defined tag. For this code the tag in ‘slide‘.
</pre> <?php $slides = array(); $args = array( 'tag' => 'slide', 'nopaging'=>true, 'posts_per_page'=>3 ); $slider_query = new WP_Query( $args ); if ( $slider_query->have_posts() ) { while ( $slider_query->have_posts() ) { $slider_query->the_post(); if(has_post_thumbnail()){ $temp = array(); $thumb_id = get_post_thumbnail_id(); $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'full', true); $thumb_url = $thumb_url_array[0]; $temp['permalink'] = get_permalink(); $temp['title'] = get_the_title(); $temp['excerpt'] = get_the_excerpt(); $temp['image'] = $thumb_url; $slides[] = $temp; } } } wp_reset_postdata(); ?> <?php if(count($slides) > 0) { ?> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <?php for($i=0;$i<count($slides);$i++) { ?> <li data-target="#carousel1-indicator" data-slide-to="<?php echo $i ?>" <?php if($i==0) { ?>class="active"<?php } ?>></li> <?php } ?> </ol> <div class="carousel-inner" role="listbox"> <?php $i=0; foreach($slides as $slide) { extract($slide); ?> <div class="item <?php if($i == 0) { ?>active<?php } ?>"> <img src="<?php echo $image ?>" alt="<?php echo esc_attr($title); ?>"> <div class="carousel-caption"> <div class="animated fadeInUp"> <h3><a href="<?php echo $permalink; ?>"><?php echo $title; ?></a></h3> </div> <div class="cap-desc animated fadeInUp"> <p></p> </div> </div> </div> <?php $i++; } ?> </div> <a class="left carousel-control" target="_blank" href="#carousel-example-generic" role="button" data-slide="prev"><span class="glyphicon glyphicon-menu-left" aria-hidden="true"></span><span class="sr-only">Previous</span></a> <a class="right carousel-control" target="_blank" href="#carousel-example-generic" role="button" data-slide="next"><span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span><span class="sr-only">Next</span></a> </div> <?php } ?>
Save this code in /parts/slider.php
To call slider.php on your front page or wherever you want:
<?php get_template_part('/parts/slider'); ?>
Now add tag slide to posts or pages you want to display in carousel and done! Enjoy ! 🙂
Spread the love