questions

Add WooCommerce cart link + total as last menu item in wp_nav_menu

Rate this post

I am trying to add a custom WooCommerce cart link with contents count and total cost as the last option in a menu.

This is my code that I am currently using:

add_filter('wp_nav_menu_header-menu_items','custom_minicart_in_main_menu', 10, 2);
function custom_minicart_in_main_menu($menu, $args) {

    $minicart_link = '<a class="custom-minicart" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( "View Your Cart" ); ?>"><?php echo sprintf ( _n( "%d item", "%d items", WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>';

    return $menu . $minicart_link;

}

Problem is, the only thing that is shown as a result is:

">cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - cart->get_cart_total(); ?>

The result should be:

Cart (#number of items) - $total cost of all products (subtotal using wc_price)

So, like this:

Cart (4) - $78.50

How can I adjust my code so that I get the desired result?

 

✔️Solution:

wp_nav_menu() – Displays a navigation menu – contains wp_nav_menu_{$menu->slug}_items filter hook.

/**
 * Filters the HTML list content for a specific navigation menu.
 *
 * @since 3.0.0
 *
 * @see wp_nav_menu()
 *
 * @param string   $items The HTML list content for the menu items.
 * @param stdClass $args  An object containing wp_nav_menu() arguments.
 */
$items = apply_filters( "wp_nav_menu_{$menu->slug}_items", $items, $args );

So to answer your question, use:

function custom_minicart_in_main_menu( $items, $args ) {
    // Get cart url
    $link_url = wc_get_cart_url();
    
    // Text
    $link_text = sprintf( __( 'Cart (%d) - %s', 'woocommerce' ), WC()->cart->cart_contents_count, WC()->cart->get_total() );
    
    // Link
    $minicart_link = '<a class="custom-minicart" href="' . $link_url . '">' . $link_text . '</a>';

    return $items . $minicart_link;

}
add_filter( 'wp_nav_menu_header-menu_items', 'custom_minicart_in_main_menu', 10, 2 );

Leave a Reply

Your email address will not be published.

Back to top button