Search code examples
notificationswoocommercecustomization

replacing "view cart" button with "proceed to checkout" button upon adding a product to cart


After product page reloads upon adding the product to cart, a notification appears on top saying "product was added to cart" followed by a "view cart" button.

However after product gets added to cart I want to direct customers to checkout page (where I'll add cart page functionality), not cart page. How can I replace the notification's link to cart with a link to checkout page?

wc_add_to_cart_message() function (in includes/wc-cart-functions.php) seems to generate this particular notification, should I override this function? If so, how?


Solution

  • try this...

    function rei_wc_add_to_cart_message( $message, $product_id ) {
        $titles = array();
    
        if ( is_array( $product_id ) ) {
            foreach ( $product_id as $id ) {
                $titles[] = get_the_title( $id );
            }
        } else {
            $titles[] = get_the_title( $product_id );
        }
    
        $titles     = array_filter( $titles );
        $added_text = sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', sizeof( $titles ), 'woocommerce' ), wc_format_list_of_items( $titles ) );
    
        // Output success messages
        if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
            $return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wp_get_referer() ? wp_get_referer() : home_url() );
            $message   = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', esc_url( $return_to ), esc_html__( 'Continue Shopping', 'woocommerce' ), esc_html( $added_text ) );
        } else {
            $message   = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', esc_url( wc_get_page_permalink( 'checkout' ) ), esc_html__( 'Proceed to Checkout', 'woocommerce' ), esc_html( $added_text ) );
        }
    
        return $message;
    }
    add_filter('wc_add_to_cart_message','rei_wc_add_to_cart_message',10,2);