Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.