如何在本地超市通过唯一标识获取客户WooCommerce购物车信息?
Hey there, this is a perfect use case for bridging WooCommerce's online cart system with your in-store operations—let's break down exactly how to build both the unique cart links and serial number lookup you need:
WooCommerce tracks every cart (even for guests who haven't logged in or placed an order) using server-side sessions. We can leverage that session's unique token to create a shareable link that pulls back the exact cart contents.
Implementation Steps
Pro tip: Always use a child theme or custom plugin to add these snippets—you won’t lose changes when your theme updates.
Add this code to your child theme’s functions.php file or a custom plugin:
// Add a cart restore link to the front-end cart page add_action( 'woocommerce_after_cart_table', 'display_cart_restore_link' ); function display_cart_restore_link() { // Initialize session if it doesn't exist $session = WC()->session; if ( !$session->has_session() ) { $session->set_customer_session_cookie( true ); } // Grab the unique session token and build the restore link $session_token = $session->get_session_token(); $restore_link = home_url( '/restore-cart/?token=' . $session_token ); // Display the link to customers echo '<div class="cart-restore-notice">'; echo '<p>Need to finish your purchase in-store? Save this link or share the token with our staff:</p>'; echo '<p><strong>Restore Link:</strong> <a href="' . esc_url( $restore_link ) . '">' . esc_url( $restore_link ) . '</a></p>'; echo '</div>'; } // Handle cart restoration when the link is visited add_action( 'template_redirect', 'restore_cart_from_token' ); function restore_cart_from_token() { if ( isset( $_GET['token'] ) && !empty( $_GET['token'] ) ) { $session_token = sanitize_text_field( $_GET['token'] ); $session_handler = WC()->session->get_handler(); // Fetch the saved session data from the database $session_data = $session_handler->get_session( $session_token ); if ( $session_data ) { // Restore the session and redirect to cart page WC()->session->set_session_token( $session_token ); WC()->session->set_session_expiry( time() + apply_filters( 'woocommerce_session_expiration', 48 * 60 * 60 ) ); WC()->session->set_customer_session_cookie( true ); wp_redirect( wc_get_cart_url() ); exit; } else { // Show error if token is invalid/expired wc_add_notice( 'Invalid or expired cart token. Please try again or build a new cart.', 'error' ); wp_redirect( wc_get_cart_url() ); exit; } } }
How It Works
- When a customer views their cart, they’ll see a unique link they can save or share with your staff.
- Visiting the link restores their exact cart (products, quantities, prices) even if they never started checkout.
- By default, sessions expire after 48 hours—you can adjust this by modifying the
48 * 60 * 60value (it’s in seconds).
If you prefer a shorter, easier-to-share serial number instead of a long link, we can generate a custom 6-digit serial tied to each cart, then build a simple admin tool for your staff to look up carts by this serial.
Add this code alongside the previous snippet:
// Generate and assign a unique serial number to each cart add_action( 'woocommerce_cart_loaded_from_session', 'assign_cart_serial_number' ); function assign_cart_serial_number() { $cart = WC()->cart; // Only assign a serial if one doesn't already exist if ( !$cart->get_meta( '_cart_serial_number' ) ) { // Create a 6-character alphanumeric serial $serial = strtoupper( substr( md5( uniqid( rand(), true ) ), 0, 6 ) ); // Ensure the serial is unique across all carts/orders while ( get_posts( array( 'meta_key' => '_cart_serial_number', 'meta_value' => $serial, 'post_type' => 'shop_order', 'post_status' => 'any', 'numberposts' => 1 ) ) ) { $serial = strtoupper( substr( md5( uniqid( rand(), true ) ), 0, 6 ) ); } // Save the serial to the cart's metadata $cart->update_meta_data( '_cart_serial_number', $serial ); $cart->save(); } } // Display the serial number on the cart page add_action( 'woocommerce_after_cart_table', 'display_cart_serial' ); function display_cart_serial() { $serial = WC()->cart->get_meta( '_cart_serial_number' ); if ( $serial ) { echo '<p><strong>Cart Serial Number:</strong> ' . esc_html( $serial ) . '</p>'; } } // Create an admin page for staff to look up carts by serial add_action( 'admin_menu', 'add_cart_serial_lookup_page' ); function add_cart_serial_lookup_page() { add_menu_page( 'Cart Serial Lookup', 'Cart Serial Lookup', 'manage_woocommerce', 'cart-serial-lookup', 'render_serial_lookup_page', 'dashicons-search', 56 ); } function render_serial_lookup_page() { $cart_contents = null; $error = ''; // Handle lookup submission if ( isset( $_POST['lookup_serial'] ) && !empty( $_POST['cart_serial'] ) ) { $serial = sanitize_text_field( $_POST['cart_serial'] ); global $wpdb; $session_table = $wpdb->prefix . 'woocommerce_sessions'; // Search sessions for the matching serial $session_results = $wpdb->get_results( $wpdb->prepare( "SELECT session_value FROM $session_table WHERE session_value LIKE %s", '%_cart_serial_number";s:' . strlen( $serial ) . ':"' . $serial . '"%' ) ); if ( !empty( $session_results ) ) { // Decode the session data to get cart contents $session_data = maybe_unserialize( $session_results[0]->session_value ); $cart_contents = $session_data['cart']; } else { $error = 'No cart found for this serial number.'; } } // Render the lookup interface echo '<div class="wrap">'; echo '<h1>Cart Serial Lookup</h1>'; if ( $error ) { echo '<div class="notice notice-error"><p>' . esc_html( $error ) . '</p></div>'; } echo '<form method="post">'; echo '<p><label for="cart_serial">Enter Cart Serial:</label> <input type="text" id="cart_serial" name="cart_serial" required></p>'; echo '<p><input type="submit" name="lookup_serial" class="button button-primary" value="Lookup Cart"></p>'; echo '</form>'; // Display cart contents if found if ( $cart_contents ) { echo '<h2>Cart Contents:</h2>'; echo '<table class="wp-list-table widefat fixed striped">'; echo '<thead><tr><th>Product</th><th>Quantity</th><th>Total Price</th></tr></thead>'; echo '<tbody>'; foreach ( $cart_contents as $item ) { $product = wc_get_product( $item['product_id'] ); echo '<tr>'; echo '<td>' . esc_html( $product->get_name() ) . '</td>'; echo '<td>' . esc_html( $item['quantity'] ) . '</td>'; echo '<td>' . wc_price( $item['line_total'] ) . '</td>'; echo '</tr>'; } echo '</tbody></table>'; // Optional: Add a button to restore the cart for checkout $session_token = WC()->session->get_session_token(); echo '<p><a href="' . esc_url( home_url( '/restore-cart/?token=' . $session_token ) ) . '" class="button button-secondary">Restore Cart for Checkout</a></p>'; } echo '</div>'; }
How It Works
- Every cart gets a unique 6-digit serial number displayed on the cart page.
- Your staff can access the "Cart Serial Lookup" page in the WooCommerce admin, enter the serial, and view the full cart contents.
- They can also restore the cart directly to process an in-person payment via WooCommerce’s checkout system.
- Extend Session Expiry: If customers might take longer than 48 hours to visit your store, add this filter to extend cart sessions to 7 days:
add_filter( 'woocommerce_session_expiration', 'extend_cart_session_length' ); function extend_cart_session_length( $expiry ) { return 7 * 24 * 60 * 60; // 7 days in seconds } - Email Serial/Link: If customers provide their email during cart creation, add a hook to auto-send them the serial and link for easy reference.
- Simplify Checkout: Once the cart is restored, your staff can use WooCommerce’s standard checkout to process cash, card, or other in-person payment methods.
内容的提问来源于stack exchange,提问作者user9370409

