Halloween Sale 15% off Ends in See the plans
PHP

Sticky Add to Cart Bar on Product Pages

Shows a slim bar with the product name, price and a buy button fixed to the bottom of the screen once the shopper scrolls past the main add to cart button.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'wp_footer', function () {
    if ( ! function_exists( 'is_product' ) || ! is_product() ) {
        return;
    }

    $product = wc_get_product( get_queried_object_id() );

    if ( ! $product || ! $product->is_purchasable() || ! $product->is_in_stock() ) {
        return;
    }
    ?>
<div id="wpide-sticky-cart" hidden style="position:fixed;left:0;right:0;bottom:0;z-index:9998;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 16px;background:#fff;box-shadow:0 -2px 10px rgba(0,0,0,.12);">
    <span style="font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?php echo esc_html( $product->get_name() ); ?></span>
    <span><?php echo wp_kses_post( $product->get_price_html() ); ?></span>
    <button type="button" class="button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>
</div>
<script>
(function () {
    var bar = document.getElementById('wpide-sticky-cart');
    var form = document.querySelector('form.cart');
    if (!bar || !form || !('IntersectionObserver' in window)) { return; }
    new IntersectionObserver(function (entries) {
        bar.hidden = entries[0].isIntersecting || entries[0].boundingClientRect.top > 0;
    }).observe(form);
    bar.querySelector('button').addEventListener('click', function () {
        form.scrollIntoView({ behavior: 'smooth', block: 'center' });
        var submit = form.querySelector('.single_add_to_cart_button');
        if (submit && form.classList.contains('cart') && !form.classList.contains('variations_form')) { submit.focus(); }
    });
})();
</script>
    <?php
} );

Notes

The button scrolls back to the product form, so variations and add-ons are still chosen normally.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.