自定义按钮,添加到购物车并自动重定向到结帐[重复]

This question already has an answer here:

I'd like to create a custom button on a product page that needs to add automatically the product i'm on into the cart and send you with that product details to the checkout page.

What i've tried so far :

<?php do_action( 'woocommerce_proceed_to_checkout' ); ?>

That doesnt send you on the checkout if you dont have at least 1 product in cart.

function add_to_cart_checkout_redirect() {
    wp_safe_redirect( get_permalink( get_option( 'woocommerce_checkout_page_id' ) ) );
    die();
}
add_action( 'woocommerce_add_to_cart',  'add_to_cart_checkout_redirect', 11 );

Also doesnt work.

Question:

Can be done? Am i wrong somewhere?

Thanks in advance.

</div>

if you can check this way may be help

$product = get_product($id);
echo "<a href='" . $product->add_to_cart_url() ."'>add to cart</a>";

Hope this help!

If you want user redirect to checkout page then add this code into your function.php file

function my_custom_add_to_cart_redirect( $url ) {

    $url = WC()->cart->get_checkout_url();
    // $url = wc_get_checkout_url(); // since WC 2.5.0

    return $url;

}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );

Hope it will solve your query .