PHP SnippetsOctober 18, 20241 MIN READ

Social Proof Notification PHP Snippet

By Spacetree Desk

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 '<div class="social-proof-notification" style="position: fixed; bottom: 20px; right: 20px; background-color: #fff; padding: 15px; border: 1px solid #ddd; border-radius: 5px; box-shadow: 0px 4px 8px rgba(0,0,0,0.1); z-index: 9999;">';
    echo esc_html( $notification );
    echo '</div>';

    // Add basic CSS and JS to fade out the notification after 5 seconds
    echo '
        <style>
            .social-proof-notification {
                display: none;
                animation: fadeInOut 8s forwards;
            }

            @keyframes fadeInOut {
                0% { opacity: 0; }
                10% { opacity: 1; }
                90% { opacity: 1; }
                100% { opacity: 0; }
            }
        </style>
        <script>
            document.addEventListener("DOMContentLoaded", function() {
                var notification = document.querySelector(".social-proof-notification");
                notification.style.display = "block";
                setTimeout(function() {
                    notification.style.display = "none";
                }, 5000); // Hide notification after 5 seconds
            });
        </script>
    ';
}

// Hook into WooCommerce before the footer to display the notification
add_action( 'wp_footer', 'display_social_proof_notification' );

				
			
Scroll to Top