Home » Php » Load Related Posts WP Dynamically Using OWL Carousel

Load Related Posts WP Dynamically Using OWL Carousel

Posted by: admin October 26, 2017 Leave a comment

Questions:

Unfortunately, I wasn’t able to find the exact solution to my problem.

I load 10 posts (for example) from the WP database like this:

<?php

$catArgs = array(
    'category__in'  => wp_get_post_categories( $post_id, $args ),
    'showposts' => 10,//display number of posts
    'orderby'   =>'rand',//display random posts
    'post__not_in'  => array($post->ID)
 ); 

$cat_post_query = new WP_Query($catArgs); 

if( $cat_post_query->have_posts() ) { 
    while ($cat_post_query->have_posts()) : $cat_post_query-
>the_post(); ?> 

<div class="owl-item">

<?php if (has_post_thumbnail()) ?>

<a rel="nofollow" class="thumbnail-link" href="<?php the_permalink() ?
>"><?php the_post_thumbnail('new_thumb'); ?>    
<p><?php the_title(); ?></a></p>

</div>

<?php endwhile; 

wp_reset_query(); } ?>

Afterwards, I use OWL Carousel plugin to slide between these ten posts:

jQuery(document).ready(function($){
  $('.owl-carousel').owlCarousel({
    loop:true,
    margin:10,
    lazyLoad: true,
    responsiveClass:true,
    responsive:{
        0:{
            items:1,
            nav:true,
            loop: false
        },
        600:{
            items:2,
            nav:true,
            loop: false
        },
        1000:{
            items:3,
            nav:true,
            loop:true
        }
    }
})
});

However, I realize that this is not a good practice to show these data in HTML at all.

What I need, is to load just two out of ten posts when the visitor is visiting my page. After he slides left or right, I want to load (for example) two more posts from the WP database.

In other words, I have 50 related posts. It’s too bad to load them all (bad SEO practice). How can I load them dynamically? I need just 2-3 posts preloaded, while all that remained I need the visitor to get by clicking the right or left arrow.

On the output, I want something like this:

<div class="owl-carousel">
<div class="owl-item">...Preloaded-1...</div>
<div class="owl-item">...Preloaded-2...</div>
<div class="owl-item">...Waiting for user clicking on arrow to load 
from DB...
</div>
<div class="owl-item">...Waiting for user clicking on arrow to load 
from DB-2...
</div>
<div class="owl-item">...Waiting for user clicking on arrow to load 
from DB-3...
</div>
</div>

I realize that the solution might be in the usage of jQuery or rather AJAX. But I’m incompetent in this matter.

Thanks for the assistance.

Answers: