[wp-hackers] Long Polling, Ajax and WordPress

Dagan Henderson Dagan.Henderson at epyllion.com
Mon Oct 31 14:28:33 UTC 2011

Alex, if you want efficiency, you'll really need to be able to control the server environment. Is this a possibility?

-----Original Message-----
From: wp-hackers-bounces at lists.automattic.com [mailto:wp-hackers-bounces at lists.automattic.com] On Behalf Of Alex Hempton-Smith
Sent: Monday, October 31, 2011 7:23 AM
To: wp-hackers at lists.automattic.com
Subject: [wp-hackers] Long Polling, Ajax and WordPress

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!)


==== 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
function(response) {
setTimeout('startPolling()', 10000);



==== 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' );



==== Ends ====
wp-hackers mailing list
wp-hackers at lists.automattic.com

More information about the wp-hackers mailing list