mardi 25 mai 2021

Add Ajax to Top Banner

I am currently developing a WooCommerce Site. I want to add a Top Banner, which displays different text relating to their cart total. The PHP code I created works great but only adjusts after refresh.

<?php
$total = WC()->cart->cart_contents_total;
$free = '40';
$needed = $free - $total;
if ($total == "0") {
echo "Kostenloser Versand ab <span style='color:#ff4f33;'>40€</span> in DE";
} elseif ($total < "40") {
echo "Nur noch <span style='color:#ff4f33;'> $needed €</span> vom kostenlosen Versand entfernt (DE)";
} else {
echo "Glückwunsch! Der Versand erfolgt in DE kostenlos!";
}
?>

The official Woo Documentation offers code to create an ajax cart

https://gist.github.com/woogists/c0a86397015b88f4ca722782a724ff6c

https://gist.github.com/woogists/9a16fd2d0c982e780a5de89c30cbbd25

My thinking was that maybe be inserting my code in place of the given code in the links above, the content of the top banner adjusts without refreshing the site. Now it sometimes kinda worked in some configurations, but only with weird glitches where some text is displayed twice.

/**
 * Show cart contents / total Ajax
 */
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );

function woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;

    ob_start();

    ?>
    <span class="cart-customlocation" <?php $total = WC()->cart->cart_contents_total; $free = '40'; $needed = $free - $total; if ($total == "0") { echo "Kostenloser Versand ab <span style='color:#ff4f33;'>40€</span> in DE"; } elseif ($total < "40") { echo "Nur noch <span style='color:#ff4f33;'> $needed €</span> vom kostenlosen Versand entfernt (DE)"; } else { echo "Glückwunsch! Der Versand erfolgt in DE kostenlos!"; } ?></span>
    <?php
    $fragments['span.cart-customlocation'] = ob_get_clean();
    return $fragments;
}

Could one tell me if this idea does or doesn't work and I have to find a new solution/ rewrite the code completely?

Aucun commentaire:

Enregistrer un commentaire