Show Post on Slider without Plugins

Use given php and JavaScript code on theme and show random post on slider. So follow simple steps and add slider on your theme.

How To Do

  • Place given php code for showing post.
<div class="slider">
<?php
$args = array(
'post_type' => 'post',
'orderby' => 'rand'
);
$query = new WP_Query($args);
while ($query->have_posts()) : $query->the_post();
?>
<div class="slide">
<a href="<?php the_permalink() ?>" title="<?php the_title_attribute() ?>">
<p> <?php the_title() ?> </p>
</a>
</div>
<?php endwhile; ?>
</div>
  • Then Save this and open footer.php file and paste JavaScript code.
<script>
var slider = document.querySelector('.slider');
var slides = document.querySelectorAll('.slide');
var currentIndex = 0;
var intervalId;

function showSlide() {
// hide all slides
for (var i = 0; i < slides.length; i++) {
slides[i].classList.remove('active');
}
var randomIndex = Math.floor(Math.random() * slides.length);
if (randomIndex === currentIndex) {
randomIndex = (randomIndex + 1) % slides.length;
}
slides[randomIndex].classList.add('active');
currentIndex = randomIndex;
}

function startSlider() {
intervalId = setInterval(showSlide, 3000);
}

function stopSlider() {
clearInterval(intervalId);
}
showSlide();
startSlider();
slider.addEventListener('mouseover', stopSlider);
slider.addEventListener('mouseout', startSlider);
</script>
  • Now and CSS code on style.css file or between <style>…. </style>.
 .slider {
position: relative;
width: 100%;
height: 50px;
overflow: hidden;
}
.slide {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.slide a {
color: white;
margin:0; padding: 0
}
.slide.active {
opacity: 1;
}
  • Then SAVE style.css file

Hope this code work perfectly. Have another type of help so contact-us. Thank You