This function fetches the latest WooCommerce order and displays the customer's name along with the product they purchased in a notification.
function display_social_proof_notification() {
// Ensure WooCommerce is active
if ( ! class_exists( 'WooCommerce' ) ) {
return;
}
// Get the latest completed order
$args = array(
'limit' => 1,
'orderby' => 'date',
'order' => 'DESC',
'status' => 'completed',
);
$orders = wc_get_orders( $args );
// If no orders found, do nothing
if ( empty( $orders ) ) {
return;
}
// Get customer name and purchased product from the latest order
$order = $orders[0];
$customer_name = $order->get_billing_first_name();
$items = $order->get_items();
foreach ( $items as $item ) {
$product_name = $item->get_name(); // Product name
break; // Use only the first product in the order
}
// Prepare the notification content
$notification = sprintf( '%s just purchased %s!', esc_html( $customer_name ), esc_html( $product_name ) );
// Output the notification HTML
echo '';
echo esc_html( $notification );
echo '';
// Add basic CSS and JS to fade out the notification after 5 seconds
echo '
';
}
// Hook into WooCommerce before the footer to display the notification
add_action( 'wp_footer', 'display_social_proof_notification' );