Shareable Cart Link
Shows a link under the cart that recreates the same cart for anyone who opens it, so customers can send a cart to a colleague or you can send ready-made carts to clients.
Opens WPIDE on
Code
add_action( 'woocommerce_after_cart_table', function () {
$parts = array();
foreach ( WC()->cart->get_cart() as $item ) {
$id = $item['variation_id'] ? $item['variation_id'] : $item['product_id'];
$parts[] = (int) $id . ':' . (int) $item['quantity'];
}
if ( ! $parts ) {
return;
}
$link = add_query_arg( 'wpide_cart', implode( ',', $parts ), wc_get_cart_url() );
printf(
'<p class="wpide-share-cart"><label for="wpide-share-cart">%1$s</label><input type="text" id="wpide-share-cart" readonly value="%2$s" onclick="this.select()" style="width:100%%"></p>',
esc_html( 'Share this cart:' ),
esc_url( $link )
);
} );
add_action( 'wp_loaded', function () {
if ( empty( $_GET['wpide_cart'] ) || ! function_exists( 'WC' ) || ! WC()->cart ) {
return;
}
$lines = array_slice( explode( ',', sanitize_text_field( wp_unslash( $_GET['wpide_cart'] ) ) ), 0, 30 );
foreach ( $lines as $line ) {
list( $id, $qty ) = array_pad( array_map( 'absint', explode( ':', $line ) ), 2, 1 );
$product = $id ? wc_get_product( $id ) : null;
if ( ! $product || ! $product->is_purchasable() || 'publish' !== get_post_status( $product->get_parent_id() ? $product->get_parent_id() : $id ) ) {
continue;
}
if ( $product->is_type( 'variation' ) ) {
WC()->cart->add_to_cart( $product->get_parent_id(), max( 1, $qty ), $id, $product->get_variation_attributes() );
} else {
WC()->cart->add_to_cart( $id, max( 1, $qty ) );
}
}
wp_safe_redirect( remove_query_arg( 'wpide_cart' ) );
exit;
}, 25 );
Notes
Opening the link adds up to 30 lines to the visitor's current cart; variations that need customer choices must be completed in the cart.
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.