1 | <?php |
---|
2 | /** |
---|
3 | * Plugin Name: Heartbeat API test plugin |
---|
4 | * Description: For testing the heartbeat API only, not suitable for production sites. Updates the comments count on the dashboard. |
---|
5 | */ |
---|
6 | |
---|
7 | |
---|
8 | add_filter( 'heartbeat_send', 'heartbeat_test_comments_count', 10, 2 ); |
---|
9 | |
---|
10 | function heartbeat_test_comments_count($data, $screen_id) { |
---|
11 | // Check if we are on the right screen |
---|
12 | if ( $screen_id != 'dashboard' ) |
---|
13 | return $data; |
---|
14 | |
---|
15 | $num_comments = wp_count_comments(); |
---|
16 | |
---|
17 | // Add data in an unique array key. |
---|
18 | // The uniqueness requirement is the same like for PHP function names used in a plugin. |
---|
19 | $data['my-comments-count'] = array( |
---|
20 | 'total-count' => number_format_i18n($num_comments->total_comments), |
---|
21 | 'approved-count' => number_format_i18n($num_comments->approved), |
---|
22 | 'pending-count' => number_format_i18n($num_comments->moderated), |
---|
23 | 'spam-count' => number_format_i18n($num_comments->spam), |
---|
24 | ); |
---|
25 | |
---|
26 | return $data; |
---|
27 | } |
---|
28 | |
---|
29 | add_action( 'admin_enqueue_scripts', 'heartbeat_test_enqueue' ); |
---|
30 | |
---|
31 | function heartbeat_test_enqueue($hook_suffix) { |
---|
32 | // Load scripts only where needed. |
---|
33 | if ( 'index.php' != $hook_suffix ) |
---|
34 | return; |
---|
35 | |
---|
36 | // Make sure the JS part of the Heartbeat API is loaded. |
---|
37 | wp_enqueue_script('heartbeat'); |
---|
38 | |
---|
39 | // Output the test JS. |
---|
40 | add_action( 'admin_print_footer_scripts', 'heartbeat_test_js', 20 ); |
---|
41 | } |
---|
42 | |
---|
43 | |
---|
44 | function heartbeat_test_js() { |
---|
45 | ?> |
---|
46 | <script> |
---|
47 | |
---|
48 | jQuery(document).ready( function($) { |
---|
49 | // Listen for the custom event "heartbeat-tick" on $(document). |
---|
50 | // Note: the event may change! |
---|
51 | // Always a good idea to add namespace. |
---|
52 | $(document).on( 'heartbeat-tick.comments-count', function(e, data) { |
---|
53 | if ( !data['my-comments-count'] ) |
---|
54 | return; |
---|
55 | |
---|
56 | $.each( data['my-comments-count'], function(key, value) { |
---|
57 | var node = $('#dashboard_right_now .' + key); |
---|
58 | // Update only when changed |
---|
59 | if ( node.html() != value ) |
---|
60 | node.html(value); |
---|
61 | }); |
---|
62 | |
---|
63 | if ( typeof console != 'undefined' ) { |
---|
64 | // Show debug info |
---|
65 | wp.heartbeat.debug = true; |
---|
66 | } |
---|
67 | |
---|
68 | }); |
---|
69 | }); |
---|
70 | |
---|
71 | </script> |
---|
72 | <?php |
---|
73 | } |
---|