Last active
January 21, 2020 09:40
-
-
Save pippinsplugins/6188027 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: EDD Heartbeat API test plugin | |
* Description: Demonstrates how to use the Heartbeat API to update the payments count on the dashboard | |
*/ | |
// Load the heartbeat JS | |
function edd_heartbeat_enqueue( $hook_suffix ) { | |
// Make sure the JS part of the Heartbeat API is loaded. | |
wp_enqueue_script( 'heartbeat' ); | |
add_action( 'admin_print_footer_scripts', 'edd_heartbeat_footer_js', 20 ); | |
} | |
add_action( 'admin_enqueue_scripts', 'edd_heartbeat_enqueue' ); | |
// Inject our JS into the admin footer | |
function edd_heartbeat_footer_js() { | |
global $pagenow; | |
// Only proceed if on the dashboard | |
if( 'index.php' != $pagenow ) | |
return; | |
?> | |
<script> | |
(function($){ | |
// Hook into the heartbeat-send | |
$(document).on('heartbeat-send', function(e, data) { | |
data['edd_heartbeat'] = 'dashboard_summary'; | |
}); | |
// Listen for the custom event "heartbeat-tick" on $(document). | |
$(document).on( 'heartbeat-tick', function(e, data) { | |
// Only proceed if our EDD data is present | |
if ( ! data['edd-payment-count'] ) | |
return; | |
// Log the response for easy proof it works | |
console.log( data['edd-payment-count'] ); | |
// Update sale count and bold it to provide a highlight | |
$('.edd_dashboard_widget .b.b-sales').text( data['edd-payment-count'] ).css( 'font-weight', 'bold' ); | |
// Return font-weight to normal after 2 seconds | |
setTimeout(function(){ | |
$('.edd_dashboard_widget .b.b-sales').css( 'font-weight', 'normal' );; | |
}, 2000); | |
}); | |
}(jQuery)); | |
</script> | |
<?php | |
} | |
// Modify the data that goes back with the heartbeat-tick | |
function edd_heartbeat_received( $response, $data ) { | |
// Make sure we only run our query if the edd_heartbeat key is present | |
if( $data['edd_heartbeat'] == 'dashboard_summary' ) { | |
// Retrieve payment count | |
$payments = edd_count_payments(); | |
// Send back the number of complete payments | |
$response['edd-payment-count'] = number_format_i18n( $payments->publish ); | |
} | |
return $response; | |
} | |
add_filter( 'heartbeat_received', 'edd_heartbeat_received', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment