Snippets: Custom WooCommerce Cart Link With Overlay for Top Bar

// Add the overlay cart code for the overlay in the site footer
// Only needed if you don't have it enabled for the main menu
function myprefix_cart_overlay_html() {
	get_template_part( 'partials/cart/cart-overlay' );
}
add_action( 'wp_footer', 'myprefix_cart_overlay_html' );

// Function displays cart
function myprefix_topbar_cart() {

	if ( ! WPEX_WOOCOMMERCE_ACTIVE ) {
		return;
	}

	// Get cart link
	$cart_id = wpex_parse_obj_id( wc_get_page_id( 'cart' ), 'page' );
	$url = get_permalink( $cart_id );

	// Add overlay link everywhere excerpt on the cart because it won't work there
	$classes = 'topbar-cart-link toggle-cart-widget';
	if ( ! is_cart() && ! is_checkout() ) {
		$classes .= ' toggle-cart-widget'; // This class triggers the overlay
	} ?>

	<a href="<?php echo esc_url( $url ); ?>" class="<?php echo $classes; ?>" title="<?php esc_html_e( 'Your Cart', 'total' ); ?>">
		<span class="fa fa-shopping-cart"></span>
		<?php
		// Show cart total items added
		echo '<span class="topbar-cart-link-total">' . WC()->cart->cart_contents_count .' </span>'; ?>
	</a>

<?php }
add_action( 'wpex_hook_topbar_inner', 'myprefix_topbar_cart', 50 );

// Function used to update cart via AJAX
function myprefix_topbar_cart_fragments( $fragments ) {
	ob_start();
	myprefix_topbar_cart();
	$fragments['.topbar-cart-link'] = ob_get_clean();
	return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'myprefix_topbar_cart_fragments' );

// Set cart style to overlay
add_filter( 'wpex_localize_array', function( $array ) {
	$array['wooCartStyle'] = 'overlay';
	return $array;
} );
All PHP snippets should be added via a child theme's functions.php file.