VigilanteBanana
5/4/2018 - 5:51 PM

Adds the WooCommerce cart icons/items to the top_nav menu area as the last item.

Adds the WooCommerce cart icons/items to the top_nav menu area as the last item and updates the top navigation WooCommerce cart link contents when an item is added via AJAX.

// Adds the WooCommerce cart icons/items to the top_nav menu area as the last item.

add_filter( 'wp_nav_menu_items', 'cart_nav_menu_items', 10, 2 );
function cart_nav_menu_items( $items, $args, $ajax = false ) {
	// Primary navigation only
	if ( ( isset( $ajax ) && $ajax ) || ( property_exists( $args, 'theme_location' ) && $args->theme_location === 'primary' ) ) {
		// WooCommerce
		if ( class_exists( 'woocommerce' ) ) {
			$css_class = 'menu-item menu-item-type-cart menu-item-type-woocommerce-cart';
			
			$items .= '<li class="' . esc_attr( $css_class ) . '">';
				$items .= '<a class="cart-contents" href="' . esc_url( WC()->cart->get_cart_url() ) . '">';
					$items .= '<i class="fa fa-shopping-cart"></i>' . ' - <span class="count">' .  wp_kses_data( sprintf( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count(), 'theme' ), WC()->cart->get_cart_contents_count() ) ) . '</span>';
				$items .= '</a>';
			$items .= '</li>';
		}
	}
	return $items;
}

// Updates the Top Navigation WooCommerce cart link contents when an item is added via AJAX.

add_filter( 'woocommerce_add_to_cart_fragments', 'custom_woocommerce_add_to_cart_fragments' );
function custom_woocommerce_add_to_cart_fragments( $fragments ) {
	// Add our fragment
	$fragments['li.menu-item-type-woocommerce-cart'] = cart_nav_menu_items( '', new stdClass(), true );
	return $fragments;
}