Skip to content

Instantly share code, notes, and snippets.

@mfields
Created December 5, 2010 19:54
Show Gist options
  • Save mfields/729405 to your computer and use it in GitHub Desktop.
Save mfields/729405 to your computer and use it in GitHub Desktop.
jQuery Post Loader for WordPress Home Page
<?php
/*
Plugin Name: mfields.org - Ajax Append Posts
Plugin URI:
Description:
Version: 0.1
Author: Michael Fields
Author URI: http://mfields.org/
Copyright 2010 Michael Fields michael@mfields.org
License GPLv2
*/
function mfields_ajax_append_posts_jquery() {
if ( is_home() ) {
wp_enqueue_script( 'jquery' );
}
}
add_action( 'wp_print_scripts', 'mfields_ajax_append_posts_jquery' );
function mfields_ajax_append_posts_query() {
if( is_admin() ) {
return false;
}
$response = array();
if ( isset( $_GET['action'] ) && 'mfields_load_posts' === $_GET['action'] ) {
global $query_string;
query_posts( $query_string . '&paged=' . $_GET['paged'] );
global $wp_query;
$response['post_count'] = (int) $wp_query->post_count;
if( have_posts() ) {
ob_start();
while( have_posts() ) {
the_post();
get_template_part( 'post', 'switchboard' );
}
$response['html'] = ob_get_contents();
ob_end_clean();
}
else {
$response['html'] = 'none';
}
print json_encode( $response );
exit;
}
return;
}
add_action( 'init', 'mfields_ajax_append_posts_query' );
function mfields_ajax_append_posts_js() {
if ( is_home() ) {
print <<< EOF
<script type="text/javascript">
jQuery( document ).ready( function( $ ) {
var page = 1;
var fetching = false;
var button = $( '#mfields-load-posts' );
var container = $( '#content' );
function mfields_ajax_get_next_posts() {
page++;
fetching = true;
$.ajax( {
url : document.location.href,
data : { 'action' : 'mfields_load_posts', 'paged' : page },
type : 'GET',
dataType : 'json',
cache : false,
success : function( response ) {
if ( 0 === response.post_count ) {
button.remove();
}
else {
container.append( response.html );
}
}
} );
};
button.click( function () {
mfields_ajax_get_next_posts();
} );
});
</script>
EOF;
}
}
add_action( 'wp_footer', 'mfields_ajax_append_posts_js' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment