This documentation explains how to enhance the live conversation updates feature by switching from AJAX polling to the WordPress Heartbeat API. The Heartbeat API reduces server load by reusing native WordPress functionality, providing a more optimized and maintainable approach.
Existing Implementation (Using AJAX Polling)
In the current implementation, AJAX polling is used to check for new messages every 20 seconds:
AJAX Call Logic (Default Values):
setInterval(function () {
var id = jQuery('.woo-single-msg').last().data('id'); // Last message ID
var wss_itemid = getParameterByName('wss-itemid'); // Item ID
var wss_orderid = getParameterByName('wss-orderid'); // Order ID
if (wss_itemid && wss_orderid) {
var data = {
'action': 'conversation_update',
'id': id,
'wss_itemid': wss_itemid,
'wss_orderid': wss_orderid
};
jQuery.post(WSS_SELL_SERVICES_PARAMS.ajax_url, data, function (response) {
response = $.parseJSON(response);
if (response.message) {
jQuery(response.message).insertAfter(jQuery('.woo-single-msg').last());
}
if (response.final_delivery) {
jQuery('.wss_final_delivery_wrap').show();
jQuery('.wss_accept_delivery').prop('disabled', false);
}
if (response.final_delivery_accept === 'true') {
location.reload();
}
});
}
}, 20000); // Runs every 20 seconds
Default Values in AJAX Implementation:
- Polling Interval: 20 seconds.
- Limitations:
- Constant polling increases server load.
- Not optimal for real-time communication.
- Delays between updates (up to 20 seconds).
New Approach: Using the WordPress Heartbeat API
The WordPress Heartbeat API offers a more efficient way to update the conversation. Heartbeat requests reuse existing functionality, reducing server overhead.
Implementation Steps
1. PHP Code: Handle Heartbeat Requests
Add the following PHP code to your theme’s functions.php or through a code snippet plugin.
// Step 1: Filter Heartbeat API to check for new messages
add_filter('heartbeat_received', 'woo_sell_service_heartbeat_update', 10, 2);
function woo_sell_service_heartbeat_update($response, $data) {
if (isset($data['wss_conversation_update'])) {
global $wpdb;
$woo_table = $wpdb->prefix . 'wss_sell_messages';
$last_msg_id = intval($data['last_msg_id']);
$woo_item_id = sanitize_text_field($data['wss_itemid']);
$woo_order_id = sanitize_text_field($data['wss_orderid']);
// Fetch new messages after the last message ID
$new_messages = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $woo_table WHERE order_id = %d AND item_id = %d AND id > %d ORDER BY id ASC",
$woo_order_id, $woo_item_id, $last_msg_id
)
);
if ($new_messages) {
ob_start();
foreach ($new_messages as $message) {
?>
<div class="woo-single-msg" data-id="<?php echo esc_attr($message->id); ?>">
<p><?php echo esc_html($message->message); ?></p>
</div>
<?php
}
$response['new_messages'] = ob_get_clean();
}
}
return $response;
}
// Step 2: Adjust Heartbeat Interval (Optional)
add_filter('heartbeat_settings', 'woo_sell_service_heartbeat_settings');
function woo_sell_service_heartbeat_settings($settings) {
$settings['interval'] = 10; // Heartbeat interval set to 10 seconds
return $settings;
}
2. JavaScript Code: Integrate with Heartbeat
Create a JavaScript file (woo-sell-service-conversation.js) and enqueue it in your theme using the following code.
add_action('wp_enqueue_scripts', 'woo_sell_service_enqueue_script');
function woo_sell_service_enqueue_script() {
wp_enqueue_script('woo-sell-service-conversation', get_template_directory_uri() . '/js/woo-sell-service-conversation.js', ['jquery', 'heartbeat'], null, true);
}
JavaScript Code: woo-sell-service-conversation.js
jQuery(window).on('heartbeat-tick', function (event, data) {
if (data.new_messages) {
jQuery(data.new_messages).insertAfter(jQuery('.woo-single-msg').last());
}
});
jQuery(window).on('load', function () {
const wss_itemid = getParameterByName('wss-itemid');
const wss_orderid = getParameterByName('wss-orderid');
if (WSS_SELL_SERVICES_PARAMS.enable_live_conversation == 1 && wss_itemid && wss_orderid) {
// Attach data to the heartbeat request
jQuery(document).on('heartbeat-send', function (event, data) {
data.wss_conversation_update = true;
data.wss_itemid = wss_itemid;
data.wss_orderid = wss_orderid;
data.last_msg_id = jQuery('.woo-single-msg').last().data('id') || 0;
});
}
});
// Helper function to get URL parameters
function getParameterByName(name) {
const url = window.location.href;
name = name.replace(/[[]]/g, '$&');
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/+/g, ' '));
}
Comparison: AJAX vs Heartbeat API
| Feature | AJAX Polling | WordPress Heartbeat API |
|---|---|---|
| Frequency | Every 20 seconds (or configured) | Default: 15 seconds (configurable) |
| Performance | Higher server load | Optimized, reuses WordPress API |
| Setup Complexity | Moderate | Simple, built into WordPress |
| Use Case | Frequent updates | Low- to medium-frequency updates |
| Code Placement | Plugin-specific | Theme or code snippets |
Advantages of Using the Heartbeat API
- Reduced Server Load: The Heartbeat API is optimized for WordPress, reducing the number of redundant requests.
- Easier Maintenance: Code resides in your theme or a code snippet, with no need to modify plugin files.
- Native WordPress Support: Reuses the Heartbeat API, avoiding the complexity of managing custom AJAX intervals.
Performance Considerations
- Do not set the interval too low (e.g., less than 5 seconds), as it may still increase server load.
- For high-traffic sites, monitor server performance to ensure the Heartbeat API runs efficiently.
Conclusion
Switching from AJAX polling to the WordPress Heartbeat API provides a more maintainable and optimized way to update conversations. This approach reduces server load while ensuring timely updates. With the code residing in your theme or a code snippet, you can easily implement this solution without altering plugin code.
