WCYVR: Heartbeat API and WP_Image_Editor

It was a pleasure to share about the Heartbeat API and WP_Image_Editor (a lightning talk) with you all at WordCamp Vancouver!

Thanks for the invitation and support!

You can find the slides and sample code after the break.
More resource links to come in an update.

If you have any questions, just let me know!

Slides

Sample Comment-Refresh Plugin from Heartbeat API Talk:

<?php
/*
	Plugin Name: Heartbeat Comment Update
	Description: Updates Comment Count on Dashboard with Heartbeat.
	Author: Andrew Ozz, Mike Schroder
	Version: 0.1
	Author URI: https://www.getsource.net
*/

add_filter( 'heartbeat_received', 'wc_heartbeat_comment_count', 10, 3 );
function wc_heartbeat_comment_count( $response, $data, $screen_id ) {

	// Check if we are on the right screen and data is requested.
	if ( $screen_id == 'dashboard' &&
			isset( $data['wc-comment-heartbeat'] ) ) {

		// Grab our data
		$num_comments = wp_count_comments();

		// Add data in an unique array key -- prefix!
		$response['wc-comment-count'] = array(
			'total-count' => number_format_i18n($num_comments->total_comments),
			'approved-count' => number_format_i18n($num_comments->approved),
			'pending-count' => number_format_i18n($num_comments->moderated),
			'spam-count' => number_format_i18n($num_comments->spam),
		);
	}

	// If the above conditions aren't met, we pass along the existing $response.
	return $response;
}


add_action( 'admin_enqueue_scripts', 'wc_heartbeat_comment_script_enqueue' );
function wc_heartbeat_comment_script_enqueue( $hook_suffix ) {
	// Load this script only in the dashboard.
	if ( 'index.php' != $hook_suffix )
		return;

	// Make sure the JS part of the Heartbeat API is loaded.
	wp_enqueue_script( 'heartbeat' );

	// Output the JavaScript we need.
	add_action( 'admin_print_footer_scripts', 'wc_heartbeat_comment_js', 20 );
}

function wc_heartbeat_comment_js() {
	?>
	<script>
	jQuery(document).ready( function($) {

		// Request comment count, using prefixed custom event.
		$(document).on( 'heartbeat-send.wp-comment-count', function( e, data ) {
			// For one-time send, use wp.heartbeat.enqueue( 'item', 'value' );
			data['wc-comment-heartbeat'] = 'count';

		// Listen for the tick custom event.
		}).on( 'heartbeat-tick.wc-comment-count', function( e, data ) {
			// Double-check we have the data we're listening for
			if ( ! data['wc-comment-count'] )
				return;

			// Replace all of the comment counts
			$.each( data['wc-comment-count'], function( key, value ) {
				$( 'span.' + key ).text( value );
			});
		});
	});
	</script>
	<?php
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.