Update Cart Value in Header (MarketPress)

Hi, I recently updated to MarketPress 3.1.1 on one of my sites and started a new install on a second site and now, the code I was using to update a cart value in the header isn't working for the site. I originally got the code from these forums (https://premium.wpmudev.org/forums/topic/shopping-cart-in-header-for-marketpress-3)

Here is the code I am using below (found in the functions.php file):

if ( ! function_exists('mp_cart_total') ) :
/**
 * Retrieve total amount in cart
 *
 * <a title="@param" href="/profile/param">param</a> string $total_type - whether to return only product total or all (include shipping & tax)
 * @return int
 */
function mp_cart_total( $total_type = 'product' ) {

	$total = 0;

		global $mp_cart;

		if ( $total_type == 'product' )
			$total = $mp_cart->product_total();
		else
			$total = $mp_cart->total();

	return apply_filters( 'mp_cart_total' , $total );
}
endif;

/**/

if ( ! function_exists('mp_cart_total_items') ) :
/**
 * Get total items in cart
 *
 * @return string
 */
function mp_cart_total_items() {
	$total = 0;
		global $mp_cart;
		if ( !empty( $mp_cart ) && $mp_cart->is_global ) {
			$raw_cart = $mp_cart->get_all_items();
			foreach ( $raw_cart as $site_id => $p_details ) {
				if ( !empty( $p_details ) && is_array( $p_details ) ) {
					foreach ($p_details as $p_id => $p_quantity) {
						$total += intval( $p_quantity );
					} // end - foreach $p_details
				} // end - $p_details
			} //end - foreach $raw_cart
		} else {
			$items = $mp_cart->get_items();
			if ( !empty( $items ) ) {
				foreach ( $items as $id => $qty ) {
					$total += intval( $qty );
				}
			}
		} // end - mp_cart
	return apply_filters( 'mp_cart_total_items' , $total );
}
endif;

/*******************************************************/

add_action( 'wp_footer', 'add_cart_value' );
function add_cart_value() {
    ?>
    <script type="text/javascript">
    jQuery(function($){
        // update cart upon ajax complete
        $(document).ajaxComplete( function( event, xhr, settings ) {
            var AjaxData = settings.data;
            if ( ( typeof AjaxData && AjaxData !== undefined ) && AjaxData.indexOf("cart_action=add_item") >= 0 ) {
                $.post( '<?php echo admin_url( 'admin-ajax.php' ); ?>', { action: 'get_cart_value' }, function(response) {
                    $('#storenav div a span').text(response);  // updates value of cart
                });
            }
        });
    });
    </script>
    <?php
}

add_action( 'wp_ajax_get_cart_value', 'get_current_cart_value' );
add_action( 'wp_ajax_nopriv_get_cart_value', 'get_current_cart_value' );
function get_cart_value( $echo = true ) {
    global $mp_cart;
    $count = 0;

    if ( empty( $mp_cart ) ) {
        $mp_cart = MP_Cart::get_instance();
    }

    $items = $mp_cart->get_items();

    if ( !empty( $items ) ) {
        foreach ( $items as $id => $qty ) {
            $count += intval( $qty );
        }
    }

    if ( $echo ){
        echo '$' . $mp_cart->product_total() . ' (' . $count . ')';
    } else{
        return '$' . $mp_cart->product_total() . ' (' . $count . ')';
    }
}

function get_current_cart_value() {

    global $mp_cart;
    $count = 0;

    if ( empty( $mp_cart ) ) {
        $mp_cart = MP_Cart::get_instance();
    }

    $items = $mp_cart->get_items();

    if ( !empty( $items ) ) {
        foreach ( $items as $id => $qty ) {
            $count += intval( $qty );
        }
    }

    if (defined('DOING_AJAX') && DOING_AJAX) {
		echo '$' . number_format((float)$mp_cart->product_total(), 2, '.', '') . ' (' . $count . ')';
        exit;
    }  // end - doing_ajax

}

My PHP for the cart in the header (found in a template file):

<div id="storenav">
				<div class="navpanel">
					<?php
					global $current_user;
					get_currentuserinfo();
					$username = $current_user->display_name;
				?> <?php
					if ( is_user_logged_in() ) {
						echo '<span>Welcome, <a href="/profile" class="menulogin">' . $username . '</a></span>';
					} else {
						echo '<span><a href="/login">LOG IN</a></span>';
					}
				?> <?php wp_nav_menu( array( 'theme_location' => 'submenu', 'menu_class' => 'subnav' ) ); ?>
				<?php
					echo '<a href="/store/cart"><img src="https://teamarms.com/images/cart.png" class="cartlink" /><span class="cartnumbers">$' . number_format((float)mp_cart_total(), 2, '.', '') . ' (' . mp_cart_total_items() .')</span></a>';
				?>
				</div>

My Rendered HTML (from the header of my page):

<div class="navpanel">
					 <span>Welcome, <a href="/profile" class="menulogin">Tadmin</a></span> <div class="menu-sub-menu-container"><ul id="menu-sub-menu" class="subnav"><li id="menu-item-156" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-156"><a href="https://teamarms.com/store/products/">Products</a></li>
<li id="menu-item-155" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-155"><a href="https://teamarms.com/store/order-status/">Order Status</a></li>
<li id="menu-item-154" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-154"><a href="https://teamarms.com/store/checkout/">Checkout</a></li>
</ul></div>				<a href="/store/cart"><img src="https://teamarms.com/images/cart.png" class="cartlink"><span class="cartnumbers">$0.00 (0)</span></a>				</div>

The last bit in the HTML is what is suppose to be updated with the value of the cart and total products on AJAX update. Can anyone help me in determining why this suddenly isn't working?

If I refresh the page, the new cart total shows up, but it doesn't add or update on AJAX. Help?

  • Marcus
    • Flash Drive

    Okay... so for SEO purposes, I moved my jQuery.js and jQueryUI.js "below the fold" to the footer. For some reason, if these two are not loaded before MP starts loading things, it throws a few errors.

    When I moved the jQuery files back to the top, I was able to get this working again. It still does not update when on the cart page, but it works.

  • Panos
    • SLS

    Hi Marcus ,

    Regarding the first issue with the total of the cart, it seems to working in my tests, only had to change
    $('#storenav_navpanel div a span').html(response); // updates value of cart
    to
    $('.navpanel .cartnumbers').html(response); // updates value of cart

    in the code you have attached in your functions.php file.

    As for moving jquery.js to footer, it's a library that many scripts from plugins rely on. If these scripts (from the plugins) are enqueued before jquery.js then they would throw errors.

    Would you mind pasting the js errors you get so we can check from which file it may be coming from?

    Thanks!
    Panos

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.