问题
I am developing an ecommerce store based on WooCommerce.
I would like to add an View Cart Below the Add To Cart Button. It would be even better if it could only shown after adding at least 1 item in the cart successfully:
//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?
Thanks.
回答1:
You can use use WC_Cart is_empty() method and wc_get_page_permalink() function:
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>';
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works.
回答2:
The code you've posted should already be displaying the cart link beneath the add to cart button.
In the example below, I'm checking the cart item count to determine whether to display a link.
Another minor update I've made is to use the WC function for retrieving 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' );
来源:https://stackoverflow.com/questions/43423819/adding-a-custom-button-after-add-to-cart-button-in-single-product-pages