Wordpress: Preload next post images
As the title says, i would like a nice bit of coding to stick in my functions that pre-loads any images that are attached to the next post.
This means that whilst my users are browsing, they page will load, but it will actua开发者_StackOverflowlly be loading the next page, so when you click-through, the images should already be there and waiting!
Think of it as 'buffering' for image.
Anyone got any thoughts on this?
Cheers!
So your visitor is on page generated by single.php. You need to put your js in there. You need to do it inside the loop because that is only place where you have post id to work with. There is only one problem, what is your next post? Post that was posted before current or after current? If visitor is going backwards you need to load images from post posted before current. Anyway you can do something like this (presuming you already have jquery loaded).
NOTE: you have to put this in the loop!
removed old code
Docs for get_adjacent_post() are here, you can set post to be in same category, and you can exclude categories.
UPDATE: I made some funny typos so here is good code, tested on my installation of wp, works with custom post types:
<?php
$next_post = get_adjacent_post(false, '', false );// set last param to true if you want post that is chronologically previous
//for debug
if(!empty($next_post)){
echo 'Next post title is: '.$next_post->post_title;
} else {
echo 'global $post is not set or no corresponding post exists';
}
$args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_parent' => $next_post->ID);
$attachments = get_posts($args);
// print attachments for debug
echo '<pre>';print_r($attachments);echo '</pre>';
?>
<script type="text/javascript">
$(document).ready(function(){
var images = '';
<?php foreach($attachments as $attachment):
$mime = $attachment->post_mime_type;
if($mime == 'image/jpeg' || $mime == 'image/gif' || $mime == 'image/png'):
?>
images += '<img src="<?php echo $attachment->guid ?>" style="display:none" />';
<? endif; endforeach; ?>
if(images != ''){
$('body').append(images);
}
});
</script>
精彩评论