Replace Add to Cart Button URL with a specific URL along with button lable on Single Product Page upon previous completed order

Viewed 16

there I am trying to change the Label of Add to Cart Button to 'View Lecture' if the customer had already purchased the product and the URL to a specific one. Below is my code snippet, it is working fine on shop page but is not working on Single Product page.

Anyone please suggest the required changes in the code so that it shall work on Single Product page too.

// function to check if a customer has bought a product (Order with "completed" status only)

   add_filter('woocommerce_loop_add_to_cart_link','add_to_cart_link_customer_has_bought');

    function add_to_cart_link_customer_has_bought() {

        global $product;

        if( empty( $product->id ) ){

            $wc_pf = new WC_Product_Factory();
            $product = $wc_pf->get_product( $id );

        }

        $current_user = wp_get_current_user();

        if( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->id ) ){

            $product_url = "https://editorials.in/package/onlinecoaching/";
            $button_label =  "View Lecture";  

        } else {

            $product_url =  $product->add_to_cart_url();  
            $button_label = $product->add_to_cart_text();

        };

        echo sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>',
            esc_url( $product_url ),
            esc_attr( $product->id ),
            esc_attr( $product->get_sku() ),
            esc_attr( isset( $quantity ) ? $quantity : 1 ),
            $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
            esc_attr( $product->product_type ),
            esc_html( $button_label )
        );

    }
0 Answers
Related