简体   繁体   中英

Is there a way I can make woocommerce_loop_add_to_cart_link not change url address but still add product to cart?

Is there a way I can still add/remove a product to my cart without the page url changing?

I have custom add to cart button on my custom Wordpress theme but as I add product to cart the url changes to http://localhost/mytheme/?add-to-cart=15. Is there a way I can avoid it and still add product to the cart?

<?php global $product;

echo apply_filters( 'woocommerce_loop_add_to_cart_link',
    sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="addtocart_nupp">Add product</a>',
        esc_url( $product->add_to_cart_url() ),
        esc_attr( $product->get_id() ),
        esc_attr( $product->get_sku() ),
        $product->is_purchasable() ? 'add_to_cart_button' : '',
        esc_attr( $product->get_type() ),
        esc_html( $product->add_to_cart_text() )
    ),
$product ); ?>

WooCommerce has a hook woocommerce_add_to_cart_redirect which is called when you add a product to your cart.

There are two arguments which you get $url where it is redirecting and $product which was added to your cart.

add_filter( 'woocommerce_add_to_cart_redirect', 'bks_add_to_cart_redirect', 10, 2 );
function bks_add_to_cart_redirect( $url, $product ) {
    if ( $product && is_a( $product, 'WC_Product' ) ) {
        // Do any change or URL you want to $url.
    }
    return $url;
}

You can change the logic and redirect it back to the product page by changing $url inside if like so.

$url = esc_url($product->get_permalink());

You can add paramters to it.

$url = esc_url( add_query_arg('name', 'value', $product->get_permalink() ) );

-- OR --

Just redirect it to a custom page.

$url = esc_url( home_url() . '/custom_page' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM