Skip to content

Instantly share code, notes, and snippets.

@generatepress
Last active September 30, 2018 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save generatepress/d52d96cf98522b815fcde4892b573d0e to your computer and use it in GitHub Desktop.
Save generatepress/d52d96cf98522b815fcde4892b573d0e to your computer and use it in GitHub Desktop.
Add number of items in cart to WooCommerce menu item
function custom_wc_cart_link() {
ob_start();
?>
<a href="<?php echo esc_url( wc_get_cart_url() ); ?>" class="cart-contents">
<?php echo sprintf ( _n( '%d', '%d', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?>
<span class="amount"><?php echo wp_kses_data( WC()->cart->get_cart_subtotal() ); ?></span>
</a>
<?php
return ob_get_clean();
}
remove_filter( 'wp_nav_menu_items','generatepress_wc_menu_cart', 10, 2 );
add_filter( 'wp_nav_menu_items', function( $nav, $args ) {
if ( $args->theme_location == 'primary' && generatepress_wc_get_setting( 'cart_menu_item' ) ) {
return sprintf(
'%1$s
<li class="wc-menu-item %4$s" title="%2$s">
%3$s
</li>',
$nav,
esc_attr__( 'View your shopping cart','generate-woocommerce' ),
custom_wc_cart_link(),
is_cart() ? 'current-menu-item' : ''
);
}
return $nav;
}, 10, 2 );
add_filter( 'woocommerce_add_to_cart_fragments', function( $fragments ) {
ob_start();
?>
<a href="<?php echo esc_url( wc_get_cart_url() ); ?>" class="cart-contents">
<?php echo sprintf ( _n( '%d', '%d', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?>
<span class="amount"><?php echo wp_kses_data( WC()->cart->get_cart_subtotal() ); ?></span>
</a>
<?php
$fragments['a.cart-contents'] = ob_get_clean();
return $fragments;
} );
@makeonlineshop
Copy link

Sorry, but what exactly is this code for ? Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment