Custom add to cart link not adding the product to cart. The cart is empty - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Wednesday, April 26, 2023

Custom add to cart link not adding the product to cart. The cart is empty

I have a function that allows me to add a custom 'Buy the Original' link on any product page. The function is triggered by an html link which calls the product by ID. It redirects to the cart page properly but the product does not add to the page. The cart comes up empty.

add_action( 'woocommerce_before_add_to_cart_button', 'custom_buy_original_link' );

function custom_buy_original_link() {
    global $product;

    // Check if the current page is a product page
    if ( is_product() ) {
        $product_name = $product->get_name();
        echo '<a href="' . esc_url( wc_get_cart_url() ) . '?add-to-cart=' . urlencode($product_name) . '">Buy the Original</a>';
    }
}

I was expecting the product called by ID to be added to the cart:

<a href="website/cart/?product_id=1232">Buy the original: $2,100</a>


source https://stackoverflow.com/questions/76085134/custom-add-to-cart-link-not-adding-the-product-to-cart-the-cart-is-empty

No comments:

Post a Comment