[wp-hackers] Long Polling, Ajax and WordPress
Alex Hempton-Smith
hempsworth at gmail.com
Mon Oct 31 14:22:51 UTC 2011
Hi all,
The project I'm working on requires an 'activity stream' of WordPress posts
to be updated live, via Ajax.
I've read a lot about long polling, Comet etc. but I've found it hard to
replicate. The code I'm using now essentially polls WordPress every 10
seconds to check if there are new posts, and then appends them to the top of
a list. This can't be very efficient, as most of the time the response from
the server will be null.
How have people achieved long-polling, or any other more efficient method to
create live streams with WP?
For reference, I have posted the code I'm using below. It's pretty simple
(but any improvements to what I have are welcomed!)
Cheers,
Alex
==== Frontend Markup ====
<ul class="activity-stream">
<li data-timestamp="1320069292">Some post</li>
<li data-timestamp="1320051123">Another post</li>
</ul>
==== Javascript ====
var startPolling = function() {
var timestamp = jQuery('.activity-stream
li:first-child').attr('data-timestamp');
var data = {
action: 'my_ajax_update_activity_stream',
latest_timestamp: timestamp
};
jQuery.post(
ajaxurl,
data,
function(response) {
jQuery('.activity-stream').prepend(response);
setTimeout('startPolling()', 10000);
});
};
jQuery(document).ready(function(){
startPolling();
});
==== functions.php ====
function filter_where( $where = '', $timestamp ) {
// Check for posts after the latest timestamp
$where .= " AND post_date > '" . date('Y-m-d H:i:s', $timestamp) . "'";
return $where;
}
function my_ajax_update_activity_stream() {
add_filter('posts_where', function($where) { return filter_where($where,
$_POST['latest_timestamp']); });
query_posts( 'post_type=myposttype&posts_per_page=-1' );
if ( have_posts() ):
while (have_posts()) : the_post();
?>
<li data-timestamp="<?php echo get_the_time('U') ?>"><?php the_content();
?></li>
<?php
endwhile;
endif;
remove_filter( 'posts_where', 'filter_where' );
exit();
}
add_action('wp_ajax_my_ajax_update_activity_stream',
'my_ajax_update_activity_stream');
==== Ends ====
More information about the wp-hackers
mailing list