Adding a custom button after adding a button to cart on single product pages

I am developing a WooCommerce based eCommerce store.

I want to add a shopping cart to view below the Add to Cart button. It would be even better if it could only show up after adding at least 1 item to the cart:

//add view cart button after add to cart button

add_action('woocommerce_after_add_to_cart_button','view_cart_store');
function view_cart_store() { ?>
    <a class="button wc-forward" href="https://example.xxx/cart/"><?php _e( 'View Shopping Cart', 'woocommerce' ) ?></a>
    <?php
}

      

How can I achieve this?

Thank.

+3


source to share


2 answers


You can use the method WC_Cart is_empty()

and wc_get_page_permalink()

:

add_action('woocommerce_after_add_to_cart_button','view_cart_store');
function view_cart_store() {
    if ( ! WC()->cart->is_empty() )
        echo '<a class="button wc-forward" href="'.wc_get_page_permalink( 'cart' ).'">'. __( 'View Shopping Cart', 'woocommerce' ) .'</a>';
}

      



The code goes in the function.php file of your active child theme (or theme), as well as any plugin file.

This code has been tested and works.

+2


source


The code you posted should already be showing the cart link under the add to cart button.

In the example below, I check the cart item count to determine whether to show a link.



Another minor update I made is using the WC function to fetch the cart url.

function wpse_view_cart_store() {
    if ( WC()->cart->get_cart_contents_count() ) : ?>

        <a class="button wc-forward" href="<?php echo esc_url( wc_get_cart_url() ); ?>"><?php _e( 'View Shopping Cart', 'woocommerce' ) ?></a>

    <?php endif;
}
add_action( 'woocommerce_after_add_to_cart_button', 'wpse_view_cart_store' );

      

0


source







All Articles