"Save Cart for Later" for Logged-In Customers
Adds a "Save cart for later" button to the cart; customers can restore the saved cart from their My Account dashboard on any device.
Opens WPIDE on
Code
add_action( 'woocommerce_cart_actions', function () {
if ( is_user_logged_in() ) {
echo '<button type="submit" class="button" name="wpide_save_cart" value="1">' . esc_html( 'Save cart for later' ) . '</button>';
}
} );
add_action( 'wp_loaded', function () {
if ( ! is_user_logged_in() || ! function_exists( 'WC' ) || ! WC()->cart ) {
return;
}
if ( isset( $_POST['wpide_save_cart'], $_POST['woocommerce-cart-nonce'] ) && wp_verify_nonce( sanitize_key( $_POST['woocommerce-cart-nonce'] ), 'woocommerce-cart' ) ) {
$saved = array();
foreach ( WC()->cart->get_cart() as $item ) {
$saved[] = array(
'product_id' => (int) $item['product_id'],
'variation_id' => (int) $item['variation_id'],
'quantity' => (int) $item['quantity'],
'variation' => array_map( 'sanitize_text_field', (array) $item['variation'] ),
);
}
update_user_meta( get_current_user_id(), '_wpide_saved_cart', array( 'time' => time(), 'items' => $saved ) );
wc_add_notice( 'Your cart has been saved. Restore it any time from your account dashboard.' );
wp_safe_redirect( wc_get_cart_url() );
exit;
}
if ( isset( $_GET['wpide_restore_cart'], $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'wpide_restore_cart' ) ) {
$saved = get_user_meta( get_current_user_id(), '_wpide_saved_cart', true );
foreach ( (array) ( $saved['items'] ?? array() ) as $item ) {
WC()->cart->add_to_cart( $item['product_id'], max( 1, $item['quantity'] ), $item['variation_id'], $item['variation'] );
}
wp_safe_redirect( wc_get_cart_url() );
exit;
}
}, 30 );
add_action( 'woocommerce_account_dashboard', function () {
$saved = get_user_meta( get_current_user_id(), '_wpide_saved_cart', true );
if ( empty( $saved['items'] ) ) {
return;
}
$count = array_sum( wp_list_pluck( $saved['items'], 'quantity' ) );
printf(
'<div class="woocommerce-info">%1$s <a class="button" href="%2$s">%3$s</a></div>',
esc_html( sprintf( 'You have a saved cart with %1$d item(s) from %2$s.', $count, wp_date( get_option( 'date_format' ), $saved['time'] ) ) ),
esc_url( wp_nonce_url( add_query_arg( 'wpide_restore_cart', 1, wc_get_cart_url() ), 'wpide_restore_cart' ) ),
esc_html( 'Restore saved cart' )
);
} );
Notes
Saving replaces any earlier saved cart, and restoring skips products that are no longer available.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.