Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/65651390/add-woocommerce-cart-link-total-as-last-menu-item-in-wp-nav-menu

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...