Get customer cart by user ID in WooCommerce

/**
 * Gets customer cart by user ID in WooCommerce.
 *
 * @see https://wpcodebook.com/woocommerce-get-cart-by-user-id/
 * @see https://woocommerce.github.io/code-reference/classes/WC-Session-Handler.html
 *
 * @return false|array Customer cart items array if found, boolean false if not.
 */
function wpcodebook_wc_get_user_cart( $user_id ) {
	$session_handler = new WC_Session_Handler();
	$session = $session_handler->get_session( $user_id );
	if (
		! $session ||
		empty( $session['cart'] ) ||
		! ( $cart = maybe_unserialize( $session['cart'] ) )
    ) {
		return false;
	}
	return $cart;
}

Example output:

Array
(
    [27b4c55047c7e1450a5dd83ccf4a6ca0] => Array
        (
            [key] => 27b4c55047c7e1450a5dd83ccf4a6ca0
            [product_id] => 48273
            [variation_id] => 0
            [variation] => Array
                (
                )

            [quantity] => 2
            [data_hash] => b5c1d5ca8bae6d4896cf1807cdf763f0
            [line_tax_data] => Array
                (
                    [subtotal] => Array
                        (
                            [33] => 3.47107438
                        )

                    [total] => Array
                        (
                            [33] => 3.47107438
                        )

                )

            [line_subtotal] => 16.52892562
            [line_subtotal_tax] => 3.47
            [line_total] => 16.52892562
            [line_tax] => 3.47
        )

    [979402d0d20fb0f8ded281a8b8687ab9] => Array
        (
            [key] => 979402d0d20fb0f8ded281a8b8687ab9
            [product_id] => 48349
            [variation_id] => 0
            [variation] => Array
                (
                )

            [quantity] => 1
            [data_hash] => b5c1d5ca8bae6d4896cf1807cdf763f0
            [line_tax_data] => Array
                (
                    [subtotal] => Array
                        (
                            [33] => 10.41322314
                        )

                    [total] => Array
                        (
                            [33] => 10.41322314
                        )

                )

            [line_subtotal] => 49.58677686
            [line_subtotal_tax] => 10.41
            [line_total] => 49.58677686
            [line_tax] => 10.41
        )

)

Leave a Comment