Admin Woo Cart Sessions

View active cart sessions and convert selected ones to Pending orders.

add_action( 'admin_menu', function() {

	$page = add_submenu_page(
		'woocommerce',
		'Cart Sessions',
		'Cart Sessions',
		'manage_woocommerce',
		'ccom_cart_sessions',
		function() {

		?>
		<div class="wrap">

		<h1>Woo Cart Sessions</h1>

		<?php

		$session_id = isset( $_GET['session_id'] )
			? sanitize_text_field( $_GET['session_id'] ) : '';

		if( $session_id ) {

			if(
				wp_verify_nonce(
					$_GET['_wpnonce'],
					'ccom_cart_sessions-' . $session_id
				)
			) {

				$order_id = ccom_cart_to_order( $session_id );

				if( $order_id ) {
					wp_admin_notice(
						'Converted session ' . $session_id . ' to order ' . $order_id,
						[ 'type' => 'success' ]
					);
				} else {
					wp_admin_notice(
						'There was an error converting the session ' . $session_id,
						[ 'type' => 'error' ]
					);					
				}

			}
		}
		?>

		<form name="ccom_cart_sessions_form" method="post">

			<?php
			wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
			wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
			?>

			<div id="poststuff">
				<div id="post-body" class="metabox-holder columns-1">
					<div id="postbox-container-1" class="postbox-container">
						<?php do_meta_boxes( '', 'normal', null );  ?>
						<?php do_meta_boxes( '', 'advanced', null ); ?>
					</div>
				</div>
			</div>

		</form>

		</div>
		<?php

	} );

	if( ! $page ) {
		return;
	}

	add_action( 'load-' . $page, function() use( $page ) {
		do_action( 'add_meta_boxes_' . $page, null );
		do_action( 'add_meta_boxes', $page, null );
		add_screen_option( 'layout_columns', [ 'max' => 1, 'default' => 1 ] );
		wp_enqueue_script( 'postbox' );
	} );

	add_action( 'admin_footer-' . $page, function() {
		?>
		<script type="text/javascript">
		postboxes.add_postbox_toggles( pagenow );
		</script>
		<?php
	} );

} );

add_action(
	'add_meta_boxes',
	function() {

		add_meta_box(
			'current-sessions',
			'Current Sessions',
			function() {

				global $wpdb;

				$table_name = $wpdb->prefix . 'woocommerce_sessions';

				$sessions = $wpdb->get_results(
					$wpdb->prepare(
						"SELECT * FROM $table_name WHERE session_expiry > %d",
						time()
					)
				);

				if( empty( $sessions ) || ! is_array( $sessions ) ) {
					echo '<p>No active WooCommerce sessions found.</p>';
				}

				printf( '<p>Viewing <strong>%d</strong> cart sessions</p>', count( $sessions ) );

				?>

				<style type="text/css">
				.wp-list-table, .wp-list-table th, .wp-list-table td {
					border: 1px solid;
					border-collapse: collapse;
					padding: 0.25em 0.5em;
					vertical-align: top;
				}
				</style>

				<table class="wp-list-table">
					<thead>
						<tr>
							<th>Guest or User ID</th>
							<th>Expires</th>
							<th>Products</th>
							<th>Name</th>
							<th>Email & Phone</th>
							<th>Billing</th>
							<th>Actions</th>
						</tr>
					</thead>
					<tbody>
						<?php

							// Loop All Sessions
							foreach( $sessions as $session ) {

								// Begin Table Row
								echo '<tr>';

								$session_id = $session->session_key; // User ID or guest hash
								$expiry_date = date( 'Y-m-d H:i:s', $session->session_expiry );
								$session_data = maybe_unserialize( $session->session_value );
								$cart = isset( $session_data['cart'] )
									? maybe_unserialize( $session_data['cart'] ) : [];
								$customer = isset( $session_data['customer'] )
									? maybe_unserialize( $session_data['customer'] ) : [];
								$notices  = isset( $session_data['notices'] )
									? maybe_unserialize( $session_data['notices'] ) : [];

								// ID Columns
								$session_link = intval( $session_id ) == $session_id
									? "<a href=\"user-edit.php?user_id=${session_id}\">${session_id}</a>"
									: $session_id;
								printf(
									'
										<td nowrap>%s</td>
										<td nowrap>%s</td>
									',
									$session_link, $expiry_date
								);

								// Cart Items Column
								echo '<td nowrap>';
								if( ! empty( $cart ) ) {
									foreach( $cart as $key => $item ) {
										$item = (object) $item;
										$product_id = $item->variation_id
											? $item->variation_id : $item->product_id;
										printf(
											'
												<div>
													<a href="post.php?post=%d&action=edit" title="%s">
														%d</a> x %d
												</div>
											',
											$product_id,
											get_the_title( $product_id ),
											$product_id,
											$item->quantity
										);
									}
								}
								echo '</td>';

								// Customer Columns
								$customer = (object) $customer;
								printf(
									'
										<td nowrap>%s %s %s</td>
										<td>%s %s</td>
										<td>%s %s %s %s %s</td>
									',
									$customer->first_name,
									$customer->last_name,
									$customer->company,
									$customer->email,
									$customer->phone,
									$customer->address,
									$customer->city,
									$customer->state,
									$customer->postcode,
									$customer->country
								);

								// Actions Column
								$actions = [];
								if( $cart && $customer->email ) {
									$actions[] = sprintf(
										'<button><a href="%s">Convert</a></button>',
										wp_nonce_url(
											'admin.php?page=ccom_cart_sessions&session_id=' . $session_id,
											'ccom_cart_sessions-' . $session_id
										)
									);
								}
								printf( '<td>%s</td>', implode( ' ', $actions ) );

								// End Table Row
								echo '</tr>';

							} // End Sessions Loop

						?>
					</tbody>
				</table>
				<?php

			},
			'woocommerce_page_ccom_cart_sessions', 'normal', 'high'
		);

	}

);

function ccom_cart_to_order( $session_id ) {

	$session_handler = new WC_Session_Handler();
	$session_data = $session_handler->get_session( $session_id );

	if( empty( $session_data ) ) {
		return false;
	}

	$cart_data = isset( $session_data['cart'] )
		? maybe_unserialize( $session_data['cart'] ) : [];
	$customer_data = isset( $session_data['customer'] )
		? maybe_unserialize( $session_data['customer'] ) : [];
	$email = isset( $customer_data['email'] )
		? sanitize_email( $customer_data['email'] ) : '';
	$phone = isset( $customer_data['phone'] )
		? sanitize_email( $customer_data['phone'] ) : '';

	$order = wc_create_order( [
		'status' => 'draft',
		'customer_id' => is_int( $session_id ) ? intval( $session_id ) : 0,
	] );

	if( is_wp_error( $order ) ) {
		return false;
	}

	$order->set_billing_email( $email );
	$order->set_billing_phone( $phone );

	$cart_item_keys_core = [
		'product_id',
		'variation_id',
		'variation',
		'quantity',
		'line_total',
		'line_subtotal',
		'line_tax',
		'line_subtotal_tax',
		'line_tax_data',
		'data',
		'data_hash',
	];

	foreach( $cart_data as $cart_item_key => $cart_item ) {

		$product_id = absint( $cart_item['product_id'] );
		$variation_id = isset( $cart_item['variation_id'] )
			? absint( $cart_item['variation_id'] ) : 0;
		$quantity = absint( $cart_item['quantity'] );
		$product = wc_get_product( $variation_id ? $variation_id : $product_id );

		if( $product ) {

			$item_id = $order->add_product( $product, $quantity, [
				'variation' => isset( $cart_item['variation'] )
					? $cart_item['variation'] : [],
				'meta_data' => isset( $cart_item['line_item_meta_data'] )
					? $cart_item['line_item_meta_data'] : [],
			] );

		}

	}

	$address_fields = [
		'first_name',
		'last_name',
		'company',
		'address_1',
		'address_2',
		'city',
		'state',
		'postcode',
		'country',
	];

	foreach( $address_fields as $field ) {
		if( isset( $customer_data[$field] ) ) {
			$order->set_address(
				[ $field => $customer_data[$field] ],
				'billing'
			);
		}
		if( isset( $customer_data['shipping_' . $field] ) ) {
			$order->set_address(
				[ $field => $customer_data['shipping_' . $field] ],
				'shipping'
			);
		}
	}

	$order->calculate_totals();
	$order->save();

	$session_handler->delete_session( $session_id );

	return $order->get_id();

}

Instructions for Admin Woo Cart Sessions

  1. Log into a staging or locally hosted clone of your site.
  2. Install and activate Code Snippets plugin.
  3. WP Admin > Snippets > Add New
  4. Copy and paste the code from the section above.
  5. Check to ensure formatting came over properly.
  6. Customize the code as desired.
  7. Add a meaningful title.
  8. Select whether to run on front-end or back-end (or both).
  9. Click “Save and Activate”.
  10. Test your site to ensure it works.
  11. Disable if any problems, or recover.
  12. Repeat for live environment.

Need help modifying Admin Woo Cart Sessions?

Contact me. I can help with fitting projects or refer to my partner.

License

All code snippets are licensed GPLv2 (or later) matching WordPress licensing.

Except when otherwise stated in writing the copyright holders and/or other parties provide the program as-is without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose.

Disclaimer of warranty