[wp-hackers] Long Polling, Ajax and WordPress

Claude Needham gxxaxx at gmail.com
Mon Oct 31 17:56:36 UTC 2011


This doesn't address the core of your issue, but I was think that:

To reduce the load on wp, would it help to create a flat file
containing information about new uploads. This could be handled by a
filter or action during the post creation process.

Then your ajax calls will not invoke all the overhead associated with
a full database inquiry.

Regards,
Claude Needham


On Mon, Oct 31, 2011 at 7:22 AM, Alex Hempton-Smith
<hempsworth at gmail.com> wrote:
> 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 ====
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
>


More information about the wp-hackers mailing list