I want to load more articles in header when user scroll to top. I use ajax to do it.
infi.php
<?php
$infinite_loop= $_POST['pcount']; ?>
<?php require('../../../../../wp-config.php');
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals(); ?>
<div>
<?php wp_reset_query(); ?>
<?php
global $wpdb;
$args = array( 'posts_per_page' => 10, 'order' => 'DESC', 'offset'=>$infinite_loop );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<div class="infiarticle box">
<div class="infithumb">
<?php the_post_thumbnail(array(300,150), true); ?>
</div>
<div>
<h2 class="post-title heading-font"> <a href="<?php echo get_permalink(); ?>"><span><?php echo the_title(); ?></span></a></h2>
</div>
</div>
<?php endforeach;
wp_reset_postdata(); ?>
</div>
Header Script
<?php if ( is_single() ): ?>
<script>
$(document).ready(function() {
var post_page_count = 0;
var height_scroll = 800;
$(window).scroll(function() {
if($(window).scrollTop() == ($(document).height() - $('body').height())) {
height_scroll = height_scroll-800;
$('a#inifiniteLoader').show('fast');
$.ajax({
type: "POST",
url: "wp-content/themes/demo/infinite.php",
data: {pcount:post_page_count},
success:
function(result){
$('a#inifiniteLoader').hide('1000');
$("#infi").append(result);
}
});
post_page_count = post_page_count+10;
}
});
});
</script>
<?php endif; ?>
Its working. I can Load data on top of header when user scroll to top. But there are some problems which I cant solved yet.
- Every time user scrolls to top, loaded content displays after the
other loaded content. For example If I scroll to top, then
article one loads in the header. After scrolling up again Article two loads correctly. But Article two is displaying after article one and I have to scroll down again
to see it. I want to display that Article Two before
Article one. How to display that new loaded content on top of other loaded content?
You need to change
$("#infi").append(result);
to$("#infi").prepend(result);
in order to insert the content at the beginning of the#infi
element.See
jQuery.prepend()
documentation.