Adding Easy Digital Download Cart Quantity to Menu

When using the popular e-commerce plugin Easy Digital Downloads it is very common you will want to add the cart quantity to the menu. There are a few ways to do this but I have found adding it to the wp_nav_menu is great for styling consistency and maintainability.

First lets look at how to get the cart quantity.


<a href="<?php echo edd_get_checkout_uri(); ?>">
    Cart (<span class="edd-cart-quantity"><?php echo edd_get_cart_quantity(); ?></span>)
</a>

The above snippet links to the checkout page. It will also update the quantity via ajax if ajax is enabled in Easy Digital Downloads and the edd-cart-quantity class is present.

The above snippet works well for general use, but a few things need to be adjusted to add it to the menu.

By utilising the items_wrap parameter that wp_nav_menu has we need to create a little function to pass in our cart quantity link so all the PHP functions output correctly.


<?php

function wdw_nav_wrap() {
    $new_nav_wrap  = '<ul id="%1$s" class="%2$s">';
    $new_nav_wrap .= '%3$s';
    $new_nav_wrap .= '<li class="menu-item">';
    $new_nav_wrap .= '<a href="' . edd_get_checkout_uri() . '">';
    $new_nav_wrap .= 'Cart (<span class="edd-cart-quantity">' . edd_get_cart_quantity() .'</span>)';
    $new_nav_wrap .= '</a>';
    $new_nav_wrap .= '</li>';
    $new_nav_wrap .= '</ul>';

    return $new_nav_wrap;
}

?>

And then we need to add that to our wp_nav_menu like so:


<?php wp_nav_menu( array(
    'theme_location' => 'primary',
    'menu_class' => 'main-menu',
    'items_wrap' => wdw_nav_wrap()
    ) ); 
?>

Want to become a better web developer?

Join over 25,000 other developer & designers who get awesome links to the best news and articles each week delivered directly to their inbox.

This post currently has no responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

Your email address will not be published. Required fields are marked *